如何用Python匹配文本文件中的单词?

6 投票
5 回答
42024 浏览
提问于 2025-04-16 13:13

我想在一个文本文件里搜索并匹配一个特定的单词。

with open('wordlist.txt', 'r') as searchfile:
        for line in searchfile:
            if word in line:
                    print line

这段代码会返回包含目标单词子串的所有单词。比如,如果目标单词是“there”,那么搜索结果会包括“there”、“therefore”、“thereby”等等。

我希望代码只返回包含“there”的行。就这样。

5 个回答

2

你可以使用正则表达式,类似下面这样:

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
  • \sthere\s - 这个意思是:在“there”前后都有空格
  • re.I - 这个表示不区分大小写
  • re.M - 在这种情况下其实没什么关系(因为每行只有一个换行符 \n)
5

把这一行文字分成一个个小块:if word in line.split():

7
import re

file = open('wordlist.txt', 'r')

for line in file.readlines():
    if re.search('^there$', line, re.I):
        print line

re.search这个函数会扫描字符串line,如果找到第一个参数中定义的正则表达式,就会返回真,并且不区分大小写,使用的是re.I。这里的^符号表示“行的开头”,而$符号表示“行的结尾”。所以,搜索函数只有在匹配到there时,前面是行的开头,后面是行的结尾,也就是说there是单独存在的情况下,才会返回真。

撰写回答