[英]Reading multiple lines from text file
我的項目的目標是計算文本文件中的所有字符。 我的代碼似乎可以工作,但它似乎只會准備好文件中的第一行代碼,而沒有其他准備。 我可以用 java 輕松完成,但我們需要使用 python,而且我對 python 的工作經驗很少
我的代碼如下:
import pandas as pd
from collections import Counter
with open ('myFile', "r") as myfile:
data=myfile.readlines()
counter = Counter(lines)
print (counter['a'])
print (counter['b'])
print (counter['c'])
print (counter['d'])
print (counter['e'])
print (counter['f'])
print (counter['g'])
print (counter['h'])
print (counter['i'])
print (counter['j'])
print (counter['k'])
print (counter['l'])
print (counter['m'])
print (counter['n'])
print (counter['o'])
print (counter['p'])
print (counter['q'])
print (counter['r'])
print (counter['s'])
print (counter['t'])
print (counter['u'])
print (counter['v'])
print (counter['w'])
print (counter['x'])
print (counter['y'])
print (counter['z'])
我不確定您的代碼中的哪些lines
,您正在將包含文本行的列表分配給data
變量。 如果要將整個文本作為單個字符串read()
,則只需使用read()
方法。
from collections import Counter
with open ('myFile', "r") as myfile:
data = myfile.read()
counter = Counter(data)
print (counter['a'])
print (counter['b'])
...
我意識到我發布的代碼來自我同時打開的兩個具有相同版本號的編輯器,這導致了錯誤。 我已經解決了這個問題(新的完整代碼如下)並且正在“工作”,我需要根據我的 Java 代碼結果檢查它。 我已經包含了代碼的結果
import pandas as pd
from collections import Counter
data = open('myFile.txt').read()
data.lower()
print (data)
counter = Counter(data)
print (counter['a'])
print (counter['b'])
print (counter['c'])
print (counter['d'])
print (counter['e'])
print (counter['f'])
print (counter['g'])
print (counter['h'])
print (counter['i'])
print (counter['j'])
print (counter['k'])
print (counter['l'])
print (counter['m'])
print (counter['n'])
print (counter['o'])
print (counter['p'])
print (counter['q'])
print (counter['r'])
print (counter['s'])
print (counter['t'])
print (counter['u'])
print (counter['v'])
print (counter['w'])
print (counter['x'])
print (counter['y'])
print (counter['z'])
我更新后的代碼的結果:
28042
3064
9280
12192
45763
3434
5143
3523
24633
1107
328
16641
8817
23809
18195
9202
3611
23139
25219
25990
19636
5302
465
1396
1257
473
您是否嘗試過類似以下的操作?
file = open("myFile.txt", "r")
data = file.read()
number_of_characters = len(data)
print('Number of characters in text file : {}'.format(number_of_characters))
file.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.