簡體   English   中英

如何使用python匹配文本文件中的單詞?

[英]How do I match a word in a text file using python?

我想搜索並匹配文本文件中的特定單詞。

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

此代碼甚至返回包含目標字的子字符串的單詞。 例如,如果單詞是“那里”,則搜索返回“那里”,“因此”,“從而”等。

我希望代碼只返回包含“there”的行。 期。

將該行拆分為標記: if word in line.split():

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 ^字符表示'行的開頭',而$字符表示'行的結尾'。 因此,搜索函數只有前面跟着行的開頭匹配時才返回true,然后是行的末尾,也就是它自己隔離。

你總是可以使用正則表達式,類似於:

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 - 在這種情況下並不重要(因為行只有1 \\ n)

你應該使用正則表達式。 Python文檔中的正則表達式howto可能是一個很好的起點。

查找re模塊(正則表達式)。 regesearch與正則表達式'那里'是你想要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM