如何在Python中搜索特定单词的文本文件
问题描述:
我想在文本文件中找到匹配存储在名为items的现有列表中的单词的单词,该列表是在前一个函数中创建的,我希望能够在下一个函数中使用列表,但我不确定如何做到这一点,我尝试使用类,但我不能正确的。我无法弄清楚其他代码的问题。我试着在没有类和列表的情况下运行它,并且用第8行中的一个单词替换第8行中的列表'items []',即使没有错误出现,它仍然没有做任何事情。当下面的代码运行时,它会输出:“请包含有效的文本文件名称:”并停在那里。如何在Python中搜索特定单词的文本文件
class searchtext():
textfile = input("Please entre a valid textfile name: ")
items = []
def __init__search(self):
with open("textfile") as openfile:
for line in openfile:
for part in line.split():
if ("items[]=") in part:
print (part)
else:
print("not found")
从包含在先前的功能,看起来像这样的话另一个文本文件创建的列表和它的作品,因为它应该,如果是任何帮助:
def createlist():
items = []
with open('words.txt') as input:
for line in input:
items.extend(line.strip().split(','))
return items
print(createlist())
答
这可能是一个位清洁剂。我觉得上课在这里是一种矫枉过正的行为。
def createlist():
items = []
with open('words.txt') as input:
for line in input:
items.extend(line.strip().split(','))
return items
print(createlist())
# store the list
word_list = createlist()
with open('file.txt') as f:
# split the file content to words (first to lines, then each line to it's words)
for word in (sum([x.split() for x in f.read().split('\n')], [])):
# check if each word is in the list
if word in word_list:
# do something with word
print word + " is in the list"
else:
# word not in list
print word + " is NOT in the list"
答
有没有像正则表达式匹配https://docs.python.org/3/howto/regex.html
items=['one','two','three','four','five'] #your items list created previously
import re
file=open('text.txt','r') #load your file
content=file.read() #save the read output so the reading always starts from begining
for i in items:
lis=re.findall(i,content)
if len(lis)==0:
print('Not found')
elif len(lis)==1:
print('Found Once')
elif len(lis)==2:
print('Found Twice')
else:
print('Found',len(lis),'times')
答
可以正则表达式使用以下方法:
>>> import re
>>> words=['car','red','woman','day','boston']
>>> word_exp='|'.join(words)
>>> re.findall(word_exp,'the red car driven by the woman',re.M)
['red', 'car', 'woman']
第二个命令创建的分隔可以接受的单词表“ |”。要在文件上运行该文件,只需替换open(your_file,'r').read()
“由该女性驱动的红色汽车”中的字符串即可。
这并不能解决任何问题。请提交一个完整的答案,而不仅仅是链接和伪代码剪辑 – 2014-12-03 11:44:31
我试图给提问者提供一个自己尝试的建议,现在这里是一个更好的详细答案 – 2014-12-04 06:01:27