目前,我正在尝试在文本文件中搜索确切的单词/短语。我正在使用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 中,我使用正则表达式来搜索特定字符串。但是,我不知道如何搜索特定短语。
在第二个函数“搜索”中,我将该行拆分为一个列表,并在其中搜索单词。但是,这将无法搜索特定短语,因为我正在 ['the','dog','walked'] 中搜索 ["dog Walking"],这不会返回正确的行。
edit:考虑到您不想匹配部分单词(“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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)