在文本文件中查找关键字并在此单词后面找到n个单词

时间:2017-10-23 15:35:36

标签: python text-mining

我正在做一个基本的文本挖掘应用程序,我需要找到一个明确的单词(关键字)并捕获这个单词之后的n个单词。例如,在本文中,我想要捕获关键字POPULATION之后的3个单词:

补充表由2016年1年微观数据列表的59个详细表格组成,其中人口 为20,000人 或更多。这些补充估算可通过美国FactFinder和人口普查局的应用程序编程接口获得,其地理汇总级别与美国社区调查相同。

下一步将分割字符串并找到数字,但这是我已经解决的问题。我试过不同的方法(正则表达式等)没有成功。我该怎么办?

3 个答案:

答案 0 :(得分:2)

将文本拆分为单词,找到关键字的索引,抓住下一个索引处的单词:

text = 'The Supplemental Tables consist of 59 detailed tables tabulated on the 2016 1-year microdata for geographies with populations of 20,000 people or more. These Supplemental Estimates are available through American FactFinder and the Census Bureau’s application programming interface at the same geographic summary levels as those in the American Community Survey.'
keyword = 'populations'
words = text.split()
index = words.index(keyword)
wanted_words = words[index + 1:index + 4]

如果您希望将三个单词wanted_words的列表放回字符串中,请使用

wanted_text = ' '.join(wanted_words)

答案 1 :(得分:1)

您可以使用nltk库。

from nltk.tokenize import word_tokenize

def sample(string, keyword, n):
    output = []
    word_list = word_tokenize(string.lower())
    indices = [i for i, x in enumerate(word_list) if x==keyword]
    for index in indices:
        output.append(word_list[index+1:index+n+1])
    return output


>>>print sample(string, 'populations', 3)
>>>[['of', '20,000', 'people']]
>>>print sample(string, 'tables', 3)
>>>[['consist', 'of', '59'], ['tabulated', 'on', 'the']]

答案 2 :(得分:1)

你有两种解决方法

1使用jieba

jieba.cut

它可以将你的句子泄露到文字

找到人口'接下来的三个单词

2使用溢出

raw = 'YOUR_TEXT_CONTENT'
raw_list = raw.split(' ')
start = raw_list.index('populations')
print(raw_list[start:start+4])