[英]Python: finding the two words following a key word
我確定我在這里遺漏了一些明顯的東西,但是我盯着這段代碼已經有一段時間了,卻找不到問題的根源。
我想搜索許多字符串,查找所有出現的某些關鍵字,並針對每個匹配,以檢索(並保存)關鍵字前后的兩個單詞。 到目前為止,我在代碼中找到了這些單詞,但是當一個字符串中出現多個關鍵字時,該代碼將返回兩個不同的列表。 如何在觀察/字符串級別匯總這些列表(以便我可以將其匹配回字符串i)?
這是一個示例和所需結果的模擬示例。 關鍵字是“ not”:
review_list=['I like this book.', 'I do not like this novel, no, I do not.']
results= [[], ['I do not like this I do not']]
當前結果(使用下面的代碼)將是:results = [[],['我不喜歡這個'],['我不喜歡]]]
這是代碼(簡化版):
for i in review_list:
if (" not " or " neither ") in i:
z = i.split(' ')
for x in [x for (x, y) in enumerate(z) if find_not in y]:
neg_1=[(' '.join(z[max(x-numwords,0):x+numwords+1]))]
neg1.append(neg_1)
elif (" not " or " neither ") not in i:
neg_1=[]
neg1.append(neg_1)
同樣,我確定這是基本的,但是作為Python新用戶,我們將不勝感激。 謝謝!
從例如字符串中僅提取單詞(刪除標點符號)
'I do not like this novel, no, I do not.'
我建議使用正則表達式:
import re
words = re.findall(r'\w+', somestring)
查找一個詞not
等於的所有索引:
indices = [i for i, w in enumerate(words) if w=='not']
為了同時獲得前兩個詞和以下兩個詞,我建議使用set
刪除重復項:
allindx = set()
for i in indices:
for j in range(max(0, i-2), min(i+3, len(words))):
allindx.add(j)
最后將所有疑問詞放入一個空格連接的字符串中:
result = ' '.join(words[i] for i in sorted(allindx))
現在,我們當然可以將所有這些花絮放到一個函數中了……:
import re
def twoeachside(somestring, keyword):
words = re.findall(r'\w+', somestring)
indices = [i for i, w in enumerate(words) if w=='not']
allindx = set()
for i in indices:
for j in range(max(0, i-2), min(i+3, len(words)):
allindx.add(j)
result = ' '.join(words(i) for i in sorted(allindx))
return result
當然,此功能僅適用於單個句子。 從句子列表中列出結果:
review_list = ['I like this book.', 'I do not like this novel, no, I do not.']
results = [twoeachside(s, 'not') for s in review_list]
assert results == [[], ['I do not like this I do not']]
最后一個assert
當然只是檢查代碼是否按您期望的方式工作:-)
編輯:實際上,從示例來看,您有點荒謬地要求結果的項目為帶有單個字符串項的列表 (如果非空,則為空),但如果它們中的字符串為空,則為空列表。 當然也可以滿足這個絕對怪異的規范...:
results = [twoeachside(s, 'not') for s in review_list]
results = [[s] if s else [] for s in results]
這根本沒有任何意義,但是,嘿,這是您的規范!-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.