如何使用python匹配文本文件中的单词?
我想搜索并匹配文本文件中的特定单词如何使用python匹配文本文件中的单词?,python,string,match,text-files,Python,String,Match,Text Files,我想搜索并匹配文本文件中的特定单词 with open('wordlist.txt', 'r') as searchfile: for line in searchfile: if word in line: print line 此代码甚至返回包含目标单词子字符串的单词。例如,如果单词是“there”,则搜索返回“there”、“Thouse”、“Three”等 我希望代码只返回包含“there”的行。句号。将行
with open('wordlist.txt', 'r') as searchfile:
for line in searchfile:
if word in line:
print line
此代码甚至返回包含目标单词子字符串的单词。例如,如果单词是“there”,则搜索返回“there”、“Thouse”、“Three”等
我希望代码只返回包含“there”的行。句号。将行拆分为标记:
如果行中有单词。拆分():
re.search
函数扫描字符串行
,如果找到第一个参数中定义的正则表达式,则返回true,忽略re.I
的大小写。^
字符表示“行首”,而$
字符表示“行尾”。因此,搜索函数只有在匹配时才会返回true,前面是行的开头,后面是行的结尾,也就是独立的。您应该使用正则表达式。Python文档中的代码可能是一个很好的起点。查找re模块(正则表达式)。使用正则表达式“there”进行重新搜索是您想要的。您始终可以使用正则表达式,大致如下:
import re
with open('wordlist.txt', 'r') as searchfile:
for line in searchfile:
if re.search( r'\sthere\s', line, re.M|re.I):
print line
-任何空格后跟“there”再后跟任何空格\s它们\s
-表示不区分大小写re.I
-在这种情况下并不重要(因为行只有1\n)re.M
^there$
更好。输入文件包含两列:例如-50677 Dedereds,类似r'\b此处\b'的内容更好<代码>\b匹配单词边界,而不使用像\s
那样的字符。
import re
with open('wordlist.txt', 'r') as searchfile:
for line in searchfile:
if re.search( r'\sthere\s', line, re.M|re.I):
print line