[英]Python extract 3 words before and 3 words after a specific list of words with a regex
[英]Extract list of words with specific character from string using regex in Python
我有一個包含單詞的字符串,每個單詞都有其自己的標記(例如NN / NNP / JJ等)。 我想使用包含NNP令牌的特定重復單詞 。 到目前為止,我的代碼:
import re
sentence = "Rapunzel/NNP Sheila/NNP let/VBD down/RP her/PP$ long/JJ golden/JJ hair/NN in Yasir/NNP"
tes = re.findall(r'(\w+)/NNP', sentence)
print(tes)
代碼的結果:
['Rapunzel', 'Sheila', 'Yasir']
我們看到,包含NNP的單詞有3個,分別是Rapunzel / NNP Sheila / NNP(彼此相鄰出現)和Yasir / NNP(與其他NNP單詞分開)。 我的問題是我需要用重復的NNP和另一個來區分單詞。 我的預期結果是:
['Rapunzel/NNP', 'Sheila/NNP'], ['Yasir/NNP']
謝謝,執行此任務的最佳方法是什么。
將組作為簡單字符串進行匹配,然后將它們拆分:
>>> [m.split() for m in re.findall(r"\w+/NNP(?:\s+\w+/NNP)*", sentence)]
[['Rapunzel/NNP', 'Sheila/NNP'], ['Yasir/NNP']]
使用其他捕獲組,您可以非常接近預期的結果。
>>> re.findall(r'((?:\w+/NNP\s*)+)', sentence)
['Rapunzel/NNP Sheila/NNP ', 'Yasir/NNP']
捕獲組((?:\\w+/NNP\\s*)+)
將所有\\w+/NNP
模式以及它們之間的可選空格組合在一起。
這是沒有任何正則表達式的替代方法。 它使用groupby
和split()
:
from itertools import groupby
string = "Rapunzel/NNP Sheila/NNP let/VBD down/RP her/PP$ long/JJ golden/JJ hair/NN in Yasir/NNP"
words = string.split()
def get_token(word):
return word.split('/')[-1]
print([list(ws) for token, ws in groupby(words, get_token) if token == "NNP"])
# [['Rapunzel/NNP', 'Sheila/NNP'], ['Yasir/NNP']]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.