[英]Python: How to print a list with labels for each item within the list
我正在为CSC课程简介做一个python项目。 我们提供了一个.txt文件,该文件基本上是200,000行的单个单词。 我们必须逐行读取文件,并计算字母表中每个字母作为单词的第一个字母出现的次数。 我已经弄清楚了计数并存储在列表中。 但是现在我需要以以下格式打印
"a:10,898 b:9,950 c:17,045 d:10,596 e:8,735
f:11,257 .... "
另一个方面是,它必须像我上面那样每行打印5个字母计数。
到目前为止,这是我正在使用的...
def main():
file_name = open('dictionary.txt', 'r').readlines()
counter = 0
totals = [0]*26
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
for i in file_name:
for n in range(0,26):
if i.startswith(alphabet[n]):
totals[n] = totals[n]+1
print(totals)
main()
该代码当前输出
[10898, 9950, 17045, 10675, 7421, 7138, 5998, 6619, 6619, 7128, 1505, 1948, 5393, 10264, 4688, 6079, 15418, 890, 10790, 20542, 9463, 5615, 2924, 3911, 142, 658]
我强烈建议使用字典来存储计数。 这将大大简化你的代码,使之更快 。 我将其留给您练习,因为这显然是家庭作业。 (其他提示: Counter
更好)。 此外,目前您的代码仅适用于小写字母,不适用于大写字母。 您需要添加其他逻辑以将大写字母视为小写字母,或者将它们独立对待。 现在,您只需忽略它们。
话虽如此,以下将完成您当前的格式:
print(', '.join('{}:{}'.format(letter, count) for letter, count in zip(alphabet, total)))
zip
接收n个列表,并生成一个包含n个元素的新元组列表,每个元素都来自输入列表之一。 join
使用提供的分隔符将字符串列表连接在一起。 并且format
使用格式说明符对字符串进行插值,以使用提供的值填充字符串中的值。
python 3.4
解决方案是在循环中将文件的行读入下面的word变量中并使用Counter
from collections import Counter
import string
words = 'this is a test of functionality'
result = Counter(map(lambda x: x[0], words.split(' ')))
words = 'and this is also very cool'
result = result + Counter(map(lambda x: x[0], words.split(' ')))
counters = ['{letter}:{value}'.format(letter=x, value=result.get(x, 0)) for x in string.ascii_lowercase]
如果您打印计数器 :
['a:3','b:0','c:1','d:0','e:0','f:1','g:0','h:0',' i:2','j:0','k:0','l:0','m:0','n:0','o:1','p:0','q: 0','r:0','s:0','t:3','u:0','v:1','w:0','x:0','y:0' ,'z:0']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.