用于编辑 csv 的简单“查找和替换”Python 脚本出现错误

用于清理 CSV 文件的非常简单的查找和替换脚本。这以前有效,但现在我遇到了几个奇怪的错误。


它接收一个 csv (Out.csv),找到一个字符串find_str并将其替换为replace_str.


运行:python3 cleanup.ph -i Out.csv给出下面粘贴的错误。


剧本:


import re


# open your csv and read as a text string

with open('Out.csv', 'r') as f:

    my_csv_text = f.read()


find_str = 'first published'

replace_str = ' '


# substitute

new_csv_str = re.sub(find_str, replace_str, my_csv_text)


# open new file and save

new_csv_path = './my_new_csv.csv' # or whatever path and name you want

with open(new_csv_path, 'w') as f:

    f.write(new_csv_str)

错误:


Traceback (most recent call last):

  File "cleanup.py", line 11, in <module>

    new_csv_str = re.sub(find_str, replace_str, my_csv_text)

  File "/usr/lib/python3.7/re.py", line 192, in sub

    return _compile(pattern, flags).sub(repl, string, count)

  File "/usr/lib/python3.7/re.py", line 286, in _compile

    p = sre_compile.compile(pattern, flags)

  File "/usr/lib/python3.7/sre_compile.py", line 764, in compile

    p = sre_parse.parse(p, flags)

  File "/usr/lib/python3.7/sre_parse.py", line 924, in parse

    p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, 0)

  File "/usr/lib/python3.7/sre_parse.py", line 420, in _parse_sub

    not nested and not items))

  File "/usr/lib/python3.7/sre_parse.py", line 813, in _parse

    source.tell() - start)

re.error: missing ), unterminated subpattern at position 1


鸿蒙传说
浏览 198回答 1
1回答

动漫人物

我在 find_str 中使用了一个 (。由于某种原因导致它不起作用。谢谢你们!!!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python