[英]Python searching for exact word/phrase within a text file
目前,我正在尝试在文本文件中搜索确切的词/短语。 我正在使用Python 3.4
这是我到目前为止的代码。
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中,我使用regex搜索特定的字符串。 但是,我不知道如何搜索特定短语。
在第二个功能search中,我将该行拆分为一个列表,然后在其中搜索单词。 但是,这将无法搜索特定的短语,因为我正在['the','dog','walked']中搜索[“ dog walked”],但不会返回正确的行。
编辑:考虑到您不想匹配部分单词(“ foo”不应该匹配“ foobar”),您需要在数据流中向前看。 这样做的代码有点尴尬,所以我认为正则表达式(您当前的regex_search带有修复程序)是解决方法:
def regex_search(filename, term):
searcher = re.compile(term + r'([^\w-]|$)').search
with open(file, 'r') as source, open("new.txt", 'w') as destination:
for line in source:
if searcher(line):
destination.write(line)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.