【发布时间】:2021-10-13 13:23:45
【问题描述】:
我是 python 新手,我想知道是否有一种有效的方法可以通过知道单词的偏移量来从文本文件中找到原始句子。假设我有一个这样的 test.txt 文件:
test.txt
Ceci est une wheat phrase corn.
Ceci est une deuxième phrase barley.
This is the third wheat word.
假设我知道“小麦”这个词的偏移量是 [13,18]。
我的代码如下所示:
import nltk
from nltk.tokenize import word_tokenize
with open("test.txt") as f:
list_phrase = f.readlines()
f.seek(0)
contents = f.read()
for index, phrase in enumerate(list_phrase):
j = word_tokenize(phrase)
if contents[13:18] in j:
print(list_phrase[index])
我的代码的输出将打印两个句子,即(“Ceci est une wheat phrase corn.”和“This is the third wheat word.”)
如何通过知道单词的偏移量来准确检测单词的真实短语?
请注意,我考虑的偏移量在许多句子(本例中为 2 个句子)之间继续存在。例如,“barley”这个词的偏移量应该是[61,67]。
上面打印的期望输出应该是:
Ceci est une wheat phrase corn.
我们知道它的偏移量是 [13,18]。
对此的任何帮助将不胜感激。非常感谢!
【问题讨论】:
-
您的代码看起来差不多。如果“小麦”包含在多个短语中,您希望发生什么?您要打印所有匹配项,还是只打印第一个匹配项?
-
你是如何得到偏移量的?可以同时收线吗?
-
@ti7--我从另一个代码中得到它。假设在这里我知道单词的偏移量并想从文本中找到它的原始句子(由许多短语组成)
-
@TimRoberts——如果小麦包含在许多短语中。我只想打印一个与其在整个文本中的偏移量匹配的短语。
标签: python nltk text-files offset