因此,我正在為我的 EPQ 創建一個分析機器人,用于計算特定主題標簽的使用次數。我將如何檢查其他單詞字串中的單詞是否包含 a #?
uj5u.com熱心網友回復:
test = " if a word in a string of other words contains a #"
if "#" in test:
print("yes")
uj5u.com熱心網友回復:
第一種方法可以使用 來檢查字串是否具有子字串in,并使用字典收集每個唯一單詞的計數:
texts = ["it's friday! #TGIF", "My favorite day! #TGIF"]
counts = {}
for text in texts:
for word in text.split(" "):
if "#" not in word:
continue
if word not in counts:
counts[word] = 0
counts[word] = 1
print(counts)
# {'#TGIF': 2}
這可以通過以下方式進一步改進:
- 用于
str.casefold()規范化不同大小寫的文本 - 使用正則運算式忽略某些字符,例如 '#tgif!' 應該被決議為“#tgif”
uj5u.com熱心網友回復:
你已經有了一個不錯的答案,所以它真的歸結為你想要最終得到什么樣的資料。這是另一個解決方案,在相同資料上使用 Pythonre模塊:
import re
texts = ["it's friday! #TGIF #foo", "My favorite day! #TGIF"]
[re.findall('#(\w )', text) for text in texts]
正則運算式需要一些時間來適應。“'#(\w )'捕獲”(帶括號)\w 在任何哈希字符 ( ) 之后的“單詞” ( '#')。它會為資料集中的每個“檔案”生成一個主題標簽串列:
[['TGIF', 'foo'], ['TGIF']]
然后你可以用這個技巧得到總數:
from collections import Counter
from itertools import chain
Counter(chain.from_iterable(finds))
產生這個類似字典的東西:
Counter({'TGIF': 2, 'foo': 1})
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/494154.html
