目前,我正在嘗試在文本文件中搜索確切的單詞/短語。我正在使用Python 3.4Python在文本文件中搜索確切的單詞/短語。 - 新手
這是我到目前爲止的代碼。
import re
def main():
fileName = input("Please input the file name").lower()
term = input("Please enter the search term").lower()
fileName = fileName + ".txt"
regex_search(fileName, term)
def regex_search(file,term):
source = open(file, 'r')
destination = open("new.txt", 'w')
lines = []
for line in source:
if re.search(term, line):
lines.append(line)
for line in lines:
destination.write(line)
source.close()
destination.close()
'''
def search(file, term): #This function doesn't work
source = open(file, 'r')
destination = open("new.txt", 'w')
lines = [line for line in source if term in line.split()]
for line in lines:
destination.write(line)
source.close()
destination.close()'''
main()
在我的功能regex_search我用正則表達式來搜索特定的字符串。但是,我不知道如何搜索特定的短語。
在第二個函數search中,我將行分割成一個列表並在那裏搜索單詞。但是,這將無法搜索特定的短語,因爲我正在搜索['the','dog','walked']中的[「dog walked」],這將不會返回正確的行。
如果你搜索「foo」和文字有「foobar的」,是考慮一場比賽?如果您搜索「富酒吧」,一行以「富」結尾,下一行以「酒吧」開頭,這是否被認爲是匹配? – 2014-12-03 23:01:46
你能提供一個輸入文件(或其內容)和感興趣的短語的例子嗎? – Marcin 2014-12-03 23:26:45
@Brian Oakley no – 2014-12-03 23:47:26