[英]Counting instances of words from a file in Python, only works for single letters
[英]How to separate words to single letters from text file python
我得到了一段文本,我必須在其中計算文本中字母的出現頻率。 但是,我似乎無法弄清楚如何將單詞分成單個字母,以便我可以計算獨特的元素並從那里確定它們的頻率。
我很抱歉沒有在文本文件中包含文本,但我得到了以下文本:
愛麗絲開始厭倦坐在她姐姐身邊無所事事:有一兩次她偷看了她姐姐正在讀的書,但里面沒有圖片或對話,
and what is the use of a book,' thought alice
?所以她在心里考慮(盡她所能,因為炎熱的天氣讓她感到非常困倦和愚蠢),制作菊花鏈的樂趣是否值得起床采摘雛菊的麻煩,突然,一只粉紅色眼睛的白色兔子從她身邊跑了過來。
沒有什么特別了不起的地方; 愛麗絲也沒有覺得聽到兔子自言自語“哦,天哪,天哪,我要遲到了。” (后來她仔細想想,她覺得她應該對此感到奇怪,但當時這一切似乎都很自然),但是當兔子真的從背心口袋里掏出一塊表,看着它,然后繼續前進,愛麗絲開始站起來,因為她的腦海里閃過一個念頭,她以前從來沒有見過一只兔子有背心口袋,也沒有見過可以從口袋里掏出手表的兔子。 她好奇地跑過田野,幸運地及時看到它從樹籬下的一個大兔子洞里蹦出來。
又過了一會兒,愛麗絲跟着它下去了,從來沒有考慮過她到底要怎么出去。
兔子洞像一條隧道一樣筆直延伸了一段路,然后突然向下傾斜,太突然了,愛麗絲還沒來得及想停下來,就發現自己掉進了一個很深的井里。
我應該分成 26 個變量 az,然后確定它們的頻率,如下所示:
到目前為止,我嘗試制作以下代碼:
# Check where the current file you are working in, is saved.
import os
os.getcwd()
#print(os.getcwd())
# 1. Change the current working directory to the place where you have saved the file.
os.chdir('C:/Users/Annik/Desktop/DTU/02633 Introduction to programming/Datafiles')
os.getcwd()
#print(os.chdir('C:/Users/Annik/Desktop/DTU/02633 Introduction to programming/Datafiles'))
# 2. Listing the content of current working directory type
os.listdir(os.getcwd())
#print(os.listdir(os.getcwd()))
#importing the file
filein = open("small_text.txt", "r") #opens the file for reading
lines = filein.readlines() #reads all lines into an array
smalltxt = "".join(lines) #Joins the lines into one big string.
import numpy as np
def letterFrequency(filename):
#counts the frequency of letters in a text
unique_elems, counts = np.unique(separate_words, return_counts=True)
return unique_elems
我只是不知道如何將文本中的字母分開,所以我可以計算獨特的元素。
您可以使用collections.Counter
直接從文本中獲取頻率。
然后就是 select 你感興趣的 26 個鍵,因為它還會包括空格和其他符號。
from collections import Counter
[...]
with open("small_text.txt", "r") as file:
text = file.read()
keys = "abcdefghijklmnopqrstuvwxyz"
c = Counter(text.lower())
# initialize occurrence with zeros to have all keys present.
occurrence = dict.fromkeys(keys, 0)
occurrence.update({k:v for k,v in c.items() if k in keys})
total = sum(occurrence.values())
frequency = {k:v/total for k,v in occurrence.items()}
[...]
處理大寫字母str.lower
也可能有用。
“我如何將單詞分成單個字母”既然你想計算你可以在 collections 中實現 python 計數器的字符數。
例如
import collections
import pprint
...
...
file_input = input('File_Name: ')
with open(file_input, 'r') as info:
count = collections.Counter(info.read().upper()) # reading file
value = pprint.pformat(count)
print(value)
...
...
這將讀取您的文件中存在的字符數 output。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.