我對編碼相當陌生,而且對regex完全陌生。 我如何使用 regex 讀取一個文本檔案,并將每個獨特的單詞設定為一個鍵,其值為該單詞(不區分大小寫)在檔案中出現的次數?它還需要能夠找到混在字符中的詞,例如。"364Hey@ 8friend99%^"將輸出'嘿'和'朋友'作為鍵。 例如,如果我的txt檔案是:
你好,我的名字是423Jeff。我的6name34 @@是 4個字母長。
我希望的結果是:
{'hello': 1, 'my': 2, 'name': 2, 'is': 2, 'jeff': 1, 'letters': 1, 'long': 1}。
uj5u.com熱心網友回復:
你不需要Regex。這就解決了這個問題
f = open("demofile.txt"/span>, "r"/span>)
d = {}
for word in f.read().split()。
word = word.lower()
word = ''.join(e for e in word if e.isalpha()
if word is not ''/span>:
if word not in d。
d[word] = 1
else:
d[word] = 1 else: d[word] = 1
print(d)
uj5u.com熱心網友回復:
祝你在編程課上好運! 你在陳述問題和期望的輸出方面做得很好。 在未來,請考慮把你的代碼也貼出來,以便社區可以幫助你的技術。 否則,看起來你只是在讓人們做你的家庭作業。
不管怎樣,這看起來是個有趣的問題,所以你可以開始了:
#!/usr/bin/env python3。
import re
from collections import defaultdict
text = "你好,我的名字是423Jeff。我的6name34 @@是4個字母長。"
count = defaultdict(int)
words = re.split("[^A-Za-z] "/span>, text)
for word in words:
if len(word) > 0:
count[ word.lower() ] = 1.
print( dict( count ))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/311652.html
標籤:
