-4

我正在从文本文件中读取行并尝试检查行中是否包含“打开”一词。如果该行中有“open”这个词,它将被留下,但如果它没有“open”这个词,则该行被写入另一个文件。

例如

We open the door
I walked through the door

在上面的示例中,不会考虑句子“We open the door”,但句子“I walk through the door”将被写入另一个文件。

4

1 回答 1

0

很难理解你到底想要什么,但我认为你想要这样的东西

with open('nopen.txt','w') as not_open_file, open('infile.txt','r') as in_file:
    for line in in_file:
        if 'open' not in line:
            not_open_file.write(line)  # file with lines that do not have open

如果您担心居住在哥本哈根的人(或其他部分单词匹配)

with open('nopen.txt','w') as not_open_file, open('infile.txt','r') as in_file:
    for line in in_file:
        if 'open' not in [word.lower() for word in re.split(r'\W+', line)]:
            not_open_file.write(line)  # file with lines that do not have open
于 2013-06-06T19:10:47.200 回答