[英]How to search a text file for a specific word in Python
我想在文本文件中找到與存儲在稱為項的現有列表中的單詞匹配的單詞,該列表是在上一個函數中創建的,並且我也希望能夠在下一個函數中使用該列表,但是我不確定如何為此,我嘗試為此使用類,但我做對了。 我無法弄清楚其余代碼的問題所在。 我嘗試在沒有類和列表的情況下運行它,並用打開的文本文件中的一個單詞替換了第8行中的列表“ items []”,盡管沒有出現錯誤,它仍然沒有執行任何操作。 運行以下代碼時,它會打印出:“請輸入一個有效的文本文件名稱:”,並在此處停止。
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())
您可以通過以下方式使用regexp:
>>> 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()
。
這可能會更清潔。 我覺得上課太誇張了。
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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.