如何使用python匹配文本文件中的单词? [英] How do I match a word in a text file using python?

查看:597
本文介绍了如何使用python匹配文本文件中的单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要搜索和匹配文本文件中的特定单词.

I want to search and match a particular word in a text file.

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

此代码甚至返回包含目标单词的子字符串的单词.例如,如果单词是"there",则搜索返回"there","there因此","thereby"等.

This code returns even the words that contain substrings of the target word. For example if the word is "there" then the search returns "there", "therefore", "thereby", etc.

我希望代码仅返回包含那里"的行.期间.

I want the code to return only the lines which contain "there". Period.

推荐答案

import re

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

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

re.search函数扫描字符串line,如果找到第一个参数中定义的正则表达式,则返回true,而忽略re.I的大小写. ^字符表示行的开始",而$字符表示行的结束".因此,仅当搜索功能与 there 相匹配时,它才返回true,在行首,行尾均与之匹配,也称为单独.

The re.search function scans the string line and returns true if it finds the regular expression defined in the first parameter, ignoring case with re.I. The ^ character means 'beginning of the line' while the $ character means 'end of the line'. Therefore, the search function will only return true if it matches there preceded by the beginning of the line, and followed by the end of the line, aka isolated on its own.

这篇关于如何使用python匹配文本文件中的单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆