我正在编写一个程序,该程序将计算每个字母的数量。
当前,它可以工作,但是它分别计算大写和小写字母。我试图将所有字符都转换为大写,但没有用。
myFile = open('textFile.txt', 'r+')
with open('textFile.txt', 'r') as fileinput:
for line in fileinput:
line = line.upper()
d = {}
for i in myFile.read():
d[i] = d.get(i,0) + 1
for k,v in sorted(d.items()):
print("{}: {}".format(k,v))
如果我的文本文件包含:
abc ABC
它将打印: (空间):1 答:1 B:1 C:1 a:1 b:1 c:1
我要打印: A2 B:2 C:2
答案 0 :(得分:0)
line = line.upper()
的结果未在任何地方使用。也许将计数代码移到执行大写转换的代码块中。然后计算每个大写字母行中的字符。
答案 1 :(得分:0)
在这种情况下,您将字符更改为大写,但仅读取文件 参见第4行,做这样的事情
<script>
var fso = new ActiveXObject("Scripting.FileSystemObject");
var f1 = fso.createtextfile("c:\myjstest.txt", true);
</script>
答案 2 :(得分:0)
这会做到的。
chars = []
with open('textFile.txt', 'r') as fileinput:
for line in fileinput:
for c in line:
chars.append(c.upper())
d = {}
for i in chars:
d[i] = d.get(i, 0) + 1
for k,v in sorted(d.items()):
print("{}: {}".format(k,v))
或者这个:
d = {}
with open('textFile.txt', 'r') as fileinput:
for line in fileinput:
line = line.upper()
for i in line:
d[i] = d.get(i,0) + 1
for k,v in sorted(d.items()):
print("{}: {}".format(k,v))
答案 3 :(得分:0)
在Python中,缩进至关重要,您要将输入转换为大写,然后将其丢弃。
尝试像这样重新排列:
d = {}
#myFile = open('textFile.txt', 'r+') - removed as not needed due to "with" variant of file processing below.
with open('textFile.txt', 'r') as fileinput:
for line in fileinput:
line = line.upper()
for i in line:
d[i] = d.get(i,0) + 1
for k,v in sorted(d.items()):
print("{}: {}".format(k,v))