在一个文本文件中找到一个关键字,然后抓住这个单词后面的n个单词

2024-10-03 02:47:16 发布

您现在位置:Python中文网/ 问答频道 /正文

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

补充表格由59个详细表格组成,这些表格以2016年1年微观数据为基础,针对人口超过20000人的地区。这些补充估计数可通过美国FactFinder和人口普查局的应用程序编程接口获得,其地理摘要级别与美国社区调查中的相同。

下一步是拆分字符串并找到数字,但这是我已经解决的问题。我尝试过不同的方法(regex等),但没有成功。我该怎么做?你知道吗


Tags: 数据文本应用程序编程关键字单词地理基础
3条回答

你有两种方法来解决它

1使用解霸

jieba.cut

它能把你的句子拼成文字

只要找到“人口”然后找到下三个词

2使用溢出

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

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

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)

你可以使用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']]

相关问题 更多 >