我有2 個檔案,Names.txt 和 Paragraph.txt
名稱.txt
約翰·安娜·羅恩·大衛
段落.txt
大衛,多年來一直在遏制你的熱情中體現拉里大衛,從技術上講,這可能會在另一個賽季回歸。然后,約翰·巴拉索、約翰·麥凱恩、約翰·圖恩、奧林·哈奇和杰夫·弗萊克一一投票贊成。
目標是遍歷帶有 Names.txt 值的 Paragraph.txt 檔案,并為在 Names.txt 中找到的每個名稱創建一個變數
4 必須創建變數,整數,每個變數的值,必須是名稱在 Paragraph.txt 中彈出的次數。
例子; 必須有一個名為 David 的變數等于 2,因為 David 這個名字在 Paragraph.txt 中出現了 2 次
我怎樣才能實作這一點,使用 for 回圈?
歡迎任何建議!
uj5u.com熱心網友回復:
使用 Python 的 re(正則運算式)庫相對容易做到這一點。
import re
output = {}
with open('Names.txt', 'r') as names_file:
with open('Paragraph.txt', 'r') as paragraph_file:
names = names_file.read().split(' ')
paragraph = paragraph_file.read()
for name in names:
output[name] = len(re.findall(name, paragraph))
print(output)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/528640.html