Skip to main content
 首页 » 编程设计

Python:搜索一对关键字前后的词

2024年10月25日9mfryf

我使用以下代码打开一个文本文件,删除 HTML,并搜索某个关键字前后的单词:

import nltk 
import re 
 
text = nltk.clean_html(open('file.txt').read()) 
text = text.lower() 
 
pattern = re.compile(r'''(?x) ([^\(\)0-9]\.)+ | \w+(-\w+)* |  \.\.\. ''') 
text = nltk.regexp_tokenize(text, pattern) 
 
#remove the digits from text 
text = [i for i in text if not i.isdigit()] 
 
# Text is now a list of words from file.txt 
# I now loop over the Text to find all words before and after a specific keyword 
 
keyword = ['foreign'] 
for i, w in enumerate(text):  #it gives to the list items numbers 
    if w in keyword: 
        before_word = text[i-5:i-1] if i > 0 else '' 
        before_word = ' '.join(word for word in before_word) 
        after_word = text[i+1:i+5] if i+1 < len(text) else '' 
        after_word = ' '.join(word for word in after_word) 
        print "%s <%s> %s" % (before_word, w, after_word) 

如果 keyword 是一个词,则此代码效果很好。但是,如果我想找到 'foreign currency' 前后的 5 个单词怎么办?问题在于,在 text 中,所有由空格分隔的单词都是 text 列表中的不同项目。我不能做 keyword = ['foreign currency']。我该如何解决这个问题?

示例 .txt 文件 here.

请您参考如下方法:

你考虑过正则表达式吗?

这将匹配并捕获 foreign currency 之前的五个词和之后的五个词

((\w+ ){5})foreign currency(( \w+){5}) 

编辑:此正则表达式会在制表符、引号、逗号、括号等处中断。 并且提供的“要查找的单词示例”没有后面的 5 个单词,因此无法匹配。

这是一个更新的正则表达式,最多 5 个词,后面有 1-5 个词,短语 使用由“非单词”字符分隔的“非空格”字符作为单词, 并将其捕获为一组,包括搜索文本:

((\S+\W){5}foreign currency(\W\S+){1,5}) 

否则,你可以尝试:

  1. 将所有文本连接成一行,没有换行符
  2. 使用 something = text.find('foreign currency') 找到该文本的第一个位置
  3. 从那里倒数,逐个字符寻找空格,共 5 个单词
  4. 从末尾向前数,逐个字符查找空格,共 5 个单词
  5. 循环所有这些,使用 something = text.find('foreign currency', previous_end_pos) 告诉它在上一步结束后开始寻找下一个实例。