我們可以使用這個正則表達式。我們將使用正則表達式
((?:\b\w+?\b\s*){0,3})[dD]ata((?:\s*\b\w+?\b){0,3})
你可以測試自己here,前後數據的每種情況後提取三個字
首先,讓我們刪除所有的話我們不比如來自絃樂。
import re
# If you're processing a lot of sentences, it's probably wise to preprocess
#the pattern, assuming that bad_words is the same for all sentences
def remove_words(sentence, bad_words):
pat = r'(?:{})'.format(r'|'.join(bad_words))
return re.sub(pat, '', sentence, flags=re.IGNORECASE)
的,我們想在每行
data_pat = r'((?:\b\w+?\b\s*){0,3})[dD]ata((?:\s*\b\w+?\b){0,3})'
res = re.findall(pat, s, flags=re.IGNORECASE)
給我們的字符串元組的列表,圍繞數據的話。我們希望在分割後得到這些字符串的列表。
from itertools import chain
list_of_words = list(chain.from_iterable(map(str.split, chain.from_iterable(map(chain, chain(res))))))
這並不美觀,但它的工作原理。基本上,我們將元組從列表中拉出,從每個元組中拉出字符串,然後分割每個字符串,然後將所有字符串從列表中拖出來,放入一個大列表中。
讓我們把這一切與你的pandas
代碼一起。 pandas
不是我最強的地方,所以如果你看到一些奇怪的東西,請不要以爲我沒有犯過一些基本的錯誤。
import re
from itertools import chain
from collections import Counter
def remove_words(sentence, bad_words):
pat = r'(?:{})'.format(r'|'.join(bad_words))
return re.sub(pat, '', sentence, flags=re.IGNORECASE)
bad_words = ['we', 'is', 'to']
sentence_list = df.Answer.apply(lambda x: remove_words(str(x), bad_words))
c = Counter()
data_pat = r'((?:\b\w+?\b\s*){0,3})data((?:\s*\b\w+?\b){0,3})'
for sentence in sentence_list:
res = re.findall(data_pat, sentence, flags=re.IGNORECASE)
words = chain.from_iterable(map(str.split, chain.from_iterable(map(chain, chain(res)))))
c.update(words)
我們正在使用的正則表達式的好處是所有複雜的部分都不關心我們使用的是什麼單詞。有輕微的變化,我們可以做一個格式字符串
base_pat = r'((?:\b\w+?\b\s*){{0,3}}){}((?:\s*\b\w+?\b){{0,3}})'
這樣
base_pat.format('data') == data_pat
所以用文字的一些列表中,我們要收集有關key_words
import re
from itertools import chain
from collections import Counter
def remove_words(sentence, bad_words):
pat = r'(?:{})'.format(r'|'.join(bad_words))
return re.sub(pat, '', sentence, flags=re.IGNORECASE)
bad_words = ['we', 'is', 'to']
sentence_list = df.Answer.apply(lambda x: remove_words(str(x), bad_words))
key_words = ['data', 'analytics']
d = {}
base_pat = r'((?:\b\w+?\b\s*){{0,3}}){}((?:\s*\b\w+?\b){{0,3}})'
for keyword in key_words:
key_pat = base_pat.format(keyword)
c = Counter()
for sentence in sentence_list:
res = re.findall(key_pat, sentence, flags=re.IGNORECASE)
words = chain.from_iterable(map(str.split, chain.from_iterable(map(chain, chain(res)))))
c.update(words)
d[keyword] = c
現在我們有一個字典d
映射關鍵字,如data
和analytics
到Counter
s映射單詞不在我們的關聯關鍵字附近的黑名單上。像
d= {'data' : Counter({ 'important' : 2,
'very' : 3}),
'analytics' : Counter({ 'boring' : 5,
'sleep' : 3})
}
至於如何獲得前10個字的東西,這是基本的東西Counter
是最好的。
key_words, _ = zip(*Counter(w for sentence in sentence_list for w in sentence.split()).most_common(10))
非常感謝你;使用我創建的字符串而不是熊貓數據框會更容易嗎? answers_str = df.Answer.apply(str) – jeangelj
我收到一條錯誤消息SyntaxError:無效的語法和一個箭頭指向s中的「words」 – jeangelj
@jeangelj我搞亂了我的複製粘貼,所以有一個缺失的括號。我編輯它,所以它現在應該工作 –