我有一个包含大量数据的文本文件。 我试图逐行读取文件,并检查每行中的任何字母是否是单词中的字母"你好"。
然后我想要打印任何不包含h,e,l,l,o的行
我的文本文件名为data.txt
到目前为止,还有更多代码:
hello = list('hello')
with open('data.txt', 'r') as file.readlines:
for line in file:
if hello not in line:
print(line)
但目前第3行产生错误; NameError:name' file'未定义
更新
hello = list('hello')
with open('data.txt', 'r') as f:
for line in f:
s = set(line)
if all(i not in s for i in hello):
print(line)
感谢您的帮助,现在已经删除了很多文本文件的行,但是#34; Epping"仍然打印,有一个" e"在其中,和#34;你好"因此应该被排除在外?
答案 0 :(得分:1)
您错误地打开了文件。
hello = list('hello')
with open('data.txt', 'r') as f:
for line in f:
s = set(line)
if all(letter not in s for letter in hello):
print(line)
答案 1 :(得分:0)
使用"这并非正确使用"。试试这个:
with open('<filename>') as f:
for line in f:
...
如果你只想要出现任何字母(不是全部),你可以使用set intersection:
hello_set = set('hello')
for line in f:
if not set(line).intersection(hello_set):
print line
或使用&#34;任何&#34;功能:
for line in f:
s = set(line)
if any(letter not in s for letter in hello):
print(line)
答案 2 :(得分:-1)
您的代码中有一些小错误。我修好了,请比较。
hello = list('hello')
with open('data.txt', 'r') as file:
for line in file:
if all(letter not in line for letter in "hello"):
print(line)