PYTHON挑战:创建一个处理.txt文件并统计每个字符出现次数的程序
我已经编写了代码,通过按照PYTHON挑战:创建一个处理.txt文件并统计每个字符出现次数的程序,python,Python,我已经编写了代码,通过按照 import collections def main(): c = collections.Counter() inFile = open("Text.txt", 'r') for line in inFile: c += collections.Counter(line) for key in c: print(key, "character occurs", c[key], "times.")
import collections
def main():
c = collections.Counter()
inFile = open("Text.txt", 'r')
for line in inFile:
c += collections.Counter(line)
for key in c:
print(key, "character occurs", c[key], "times.")
inFile.close()
main()
这段代码完成了任务,但是,它包含10行可执行代码-我需要找到一种方法,用4行或更少的代码来完成这项任务。。。代码行包括模块导入、函数定义和函数调用。压缩编程结构以使代码适合更少的行是不行的:
例:
我一辈子都搞不清楚这件事。有人有什么想法吗?使用列表理解:
# try to figure out how to count occurances in a string
rare = [letter for letter in letters if count_is_one]
这种方法适用于使用字典类型的数据类型 关键事项:
作为f
,因为它会自动关闭文件
当区块结束时。因此,您不需要使用一条线来关闭
文件好的,从你的代码开始:
import collections
def main():
c = collections.Counter()
inFile = open("Text.txt", 'r')
for line in inFile:
c += collections.Counter(line)
for key in c:
print(key, "character occurs", c[key], "times.")
inFile.close()
main()
我们可以删除主函数并调用:
import collections
c = collections.Counter()
inFile = open("Text.txt", 'r')
for line in inFile:
c += collections.Counter(line)
for key in c:
print(key, "character occurs", c[key], "times.")
inFile.close()
这使我们净赚了2条线——减至8条。我们还可以使用带有上下文管理器的,在文件关闭时保存一行:
import collections
c = collections.Counter()
with open("Text.txt", 'r') as inFile:
for line in inFile:
c += collections.Counter(line)
for key in c:
print(key, "character occurs", c[key], "times.")
降到7。我们还可以创建单个计数器
对象,对整个文件内容进行初始化,而不是创建一个并使用每行中的值对其进行更新:
import collections
with open("Text.txt", 'r') as inFile:
c = collections.Counter(inFile.read())
for key in c:
print(key, "character occurs", c[key], "times.")
降到5。我们也可以作弊,将最后一个for循环和body放在同一行:
import collections
with open("Text.txt", 'r') as inFile:
c = collections.Counter(inFile.read())
for key in c: print(key, "character occurs", c[key], "times.")
这给了我们4行代码,但它可能违反了“压缩编程结构以使代码适合更少的行”规则。我们可以通过以下方式减少欺骗行为:
import collections
with open("Text.txt", 'r') as inFile:
c = collections.Counter(inFile.read())
print('\n'.join("{!r} character occurs {} times".format(k,v) for k,v in c.items()))
这不是最漂亮的,但有四行
当然,您可以更进一步,跳过中间c
对象的创建:
import collections
with open("Text.txt", 'r') as inFile:
print('\n'.join("{!r} character occurs {} times".format(k,v) for k,v in collections.Counter(inFile.read()).items()))
如果你不在乎关闭文件:
import collections
print('\n'.join("{!r} character occurs {} times".format(k,v) for k,v in collections.Counter(open("Text.txt", 'r').read()).items()))
要使用导入转到一行,您可以使用Kevin在评论中建议的创造性(疯狂)解决方案。我可以在一行中完成。这使用集合和听写理解来完成。它还使用setwise差分过滤掉换行符。我猜你不想数换行
print {i:open("foo.txt").read().count(i) for i in set(open("foo.txt").read())-{"\n"}}
它打印出一本漂亮的字典:
{'a': 5, 'b': 1, 'e': 2, 'g': 5, 'f': 2, 'i': 2, 'h': 2, 'k': 1, '.': 4, 'p': 4, 's': 3, 'r': 1, ':': 4, 'y': 2, 'n': 6, 'z': 1}
这将打印出文件input.txt
中的每个字符及其出现次数
input.txt
:
hsvkjlheswufWEJHBKJDHEEIUIneeiww..ziep
代码行:
temp = [print(letter, (len(open('input.txt', 'r').read())-len(open('input.txt', 'r').read().replace(letter, '')))) for letter in sorted(set(open('input.txt', 'r').read()))]
结果:
. 2
B 1
D 1
E 3
H 2
I 2
J 2
K 1
U 1
W 1
e 4
f 1
h 2
i 2
j 1
k 1
l 1
n 1
p 1
s 2
u 1
v 1
w 3
z 1
如果你的代码是有效的,那么问为什么四行或更少的代码?我只是好奇。如何print(“\n”。join({}发生{}次)。在{uuuuu导入{uuuuuuu(“集合”)中为k,v设置格式(k,v)。计数器(open(“text.txt”).read()).items())
不,我想知道如何解决这个问题的技巧。不希望sassVoting关闭,因为很难确定一个好的答案,而且模糊的提示列表不太可能帮助未来的访问者堆积溢出。
temp = [print(letter, (len(open('input.txt', 'r').read())-len(open('input.txt', 'r').read().replace(letter, '')))) for letter in sorted(set(open('input.txt', 'r').read()))]
. 2
B 1
D 1
E 3
H 2
I 2
J 2
K 1
U 1
W 1
e 4
f 1
h 2
i 2
j 1
k 1
l 1
n 1
p 1
s 2
u 1
v 1
w 3
z 1