我已经编写了代码,通过执行
的操作来完成此任务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行代码或更少的代码中执行此操作...代码行包括模块导入,函数定义和函数调用。压缩编程结构以使代码适合更少的行是不可能的:
前:
for i in range(20): code...
def main(): code ....
我不能为我的生活弄清楚这一点。有人有什么想法吗?
答案 0 :(得分:3)
好的,从您的代码开始:
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行。我们还可以使用with
上下文管理器在文件结束时保存一行:
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.我们还可以创建一个Counter
对象,对整个文件内容进行初始化,而不是创建一个并使用每行的值更新它:
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.我们也可以作弊并将最后一个用于循环和身体放在同一行:
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()))
这不是最漂亮的,但它是4行。
当然,您可以更进一步,跳过中间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()))
要使用导入转到1行,您可以使用Kevin在评论中建议的创意(和疯狂)解决方案。
答案 1 :(得分:0)
使用列表理解:
# try to figure out how to count occurances in a string
rare = [letter for letter in letters if count_is_one]
答案 2 :(得分:0)
该方法适用于使用字典类型的数据类型。
关键词:
with open() as f
因为它会自动关闭文件
当块结束时所以你不需要用一条线来关闭
文件。代码:
with open("example_file.txt", 'r') as f:
contents = f.read()
counts = dict( (c, contents.count(c)) for c in set(contents) )
for key in counts: print "%s occurred %d times" % (key, counts[key])
答案 3 :(得分:0)
我可以在一行中完成。这使用集合和字典理解来做到这一点。它还使用setwise difference过滤掉换行符。我假设你不想计算换行符。
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}
答案 4 :(得分:0)
这将打印出文件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