这是我正在使用的文本文件的示例:
<Opera>
Tristan/NNP
and/CC
Isolde/NNP
and/CC
the/DT
fatalistic/NN
horns/VBZ
The/DT
passionate/JJ
violins/NN
And/CC
ominous/JJ
clarinet/NN
;/:
正斜杠之后的大写字母是奇怪的标签。我希望能够在文件中搜索类似"NNP,CC,NNP"
的内容并让程序返回此段"Tristan and Isolde"
,连续三行中的三个单词与行中的三个标记匹配。
我遇到的问题是我希望搜索字符串是用户输入的,因此它总是不同的 我可以阅读该文件并查找一个匹配但我不知道如何从该点向后计数以打印第一个单词或如何查找下一个标记是否匹配。
答案 0 :(得分:1)
>>> import re
>>> s = "Tristan/NNP and/CC Isolde/NNP and/CC the/DT fatalistic/NN horns/VBZ The/DT passionate/JJ violins/NN And/CC ominous/JJ clarinet/NN ;/:"
>>> re.findall("(\w+)/NNP (\w+)/CC (\w+)/NNP", s)
[('Tristan', 'and', 'Isolde')]
同样,你可以做你需要的。
编辑:更广泛。
>>> import re
>>> pattern = 'NNP,CC,NNP'
>>> pattern = pattern.split(",")
>>> p = ""
>>> for i in pattern:
... p = p + r"(\w+)/"+i+ r"\n"
>>> f = open("yourfile", "r")
>>> s = f.read()
>>> f.close()
>>> found = re.findall(p, s, re.MULTILINE)
>>> found #Saved in found
[('Tristan', 'and', 'Isolde')]
>>> found_str = " ".join(found[0]) #Converted to string
>>> f = open("written.txt", "w")
>>> f.write(found_str)
>>> f.close()
答案 1 :(得分:1)
从要搜索的标记列表中动态构建正则表达式:
text = ("Tristan/NNP and/CC Isolde/NNP and/CC the/DT fatalistic/NN horns/VBZ "
"The/DT passionate/JJ violins/NN And/CC ominous/JJ clarinet/NN")
tags = ["NNP", "CC", "NNP"]
tags_pattern = r"\b" + r"\s+".join(r"(\w+)/{0}".format(tag) for tag in tags) + r"\b"
# gives you r"\b(\w+)/NNP\s+(\w+)/CC\s+(\w+)/NNP\b"
from re import findall
print(findall(tags_pattern, text))
答案 2 :(得分:0)
您的源文本似乎可能由Natural Language Toolkit (nltk)生成。
使用nltk,您可以对文本进行标记,将标记拆分为(word,part_of_speech)元组,并迭代ngrams以查找与模式匹配的文本:
import nltk
pattern = 'NNP,CC,NNP'
pattern = [pat.strip() for pat in pattern.split(',')]
text = '''Tristan/NNP and/CC Isolde/NNP and/CC the/DT fatalistic/NN horns/VBZ
The/DT passionate/JJ violins/NN And/CC ominous/JJ clarinet/NN ;/:'''
tagged_token = [nltk.tag.str2tuple(word) for word in nltk.word_tokenize(text)]
for ngram in nltk.ingrams(tagged_token,len(pattern)):
if all(gram[1] == pat for gram,pat in zip(ngram,pattern)):
print(' '.join(word for word, pos in ngram))
产量
Tristan and Isolde
相关链接: