App*_*pps 4 python string match text-files
我想搜索并匹配文本文件中的特定单词.
with open('wordlist.txt', 'r') as searchfile:
for line in searchfile:
if word in line:
print line
Run Code Online (Sandbox Code Playgroud)
此代码甚至返回包含目标字的子字符串的单词.例如,如果单词是"那里",则搜索返回"那里","因此","从而"等.
我希望代码只返回包含"there"的行.期.
import re
file = open('wordlist.txt', 'r')
for line in file.readlines():
if re.search('^there$', line, re.I):
print line
Run Code Online (Sandbox Code Playgroud)
该re.search函数扫描字符串line并返回true,如果它找到第一个参数中定义的正则表达式,忽略大小写re.I.的^字符指而"该行的开头" $字符表示"行结束".因此,搜索函数只有在前面跟着行的开头匹配时才返回true ,然后是行的末尾,也就是它自己隔离.
| 归档时间: |
|
| 查看次数: |
28425 次 |
| 最近记录: |