我在txt文件中有一个介词列表。我正在创建一个函数,以便它将从字符串中提取介词后面的单词。由于介词很多,直接把它们放到 re.compile 中是不可行的。所以我正在使用 txt 文件。这是我的代码:
with open("Input.txt"):
words = "|".join(line.rstrip() for line in open)
pattern = re.compile('{}s(w+|d+w+)sw+'.format(words))
其中 {} 表示准备的匹配,而 \s 是一个空格,后跟一个单词或数字和单词的组合,如第 20 个十字等。我得到的错误是
TypeError Traceback (most recent call last)
<ipython-input-43-0aed517ef1ba> in <module>()
1 with open("Input.txt"):
----> 2 words = "|".join(line.rsplit() for line in open)
3 pattern = re.compile("{}s(w+|d+w+)sw+".format(words))
TypeError: 'builtin_function_or_method' object is not iterable
输入.txt文件的内容为['近','上方','朝向'...]等..我如何迭代它??
代码正在迭代open
函数。您应该插入文件对象以获取行。
rsplit
似乎是rstrip
的错字.
with open("Input.txt") as f:
words = "|".join(line.rstrip() for line in f)
pattern = re.compile(r'(?:{})s(w+|d+w+)sw+'.format(words))
如果单词包含一些在正则表达式中具有特殊含义的字符,则应使用 re.escape
对其进行转义。
with open("Input.txt") as f:
words = "|".join(re.escape(line.rstrip()) for line in f)
pattern = re.compile(r'(?:{})s(w+|d+w+)sw+'.format(words))