即使它是1,也要加入信

时间:2014-11-29 16:50:49

标签: python python-3.x

wordFile = open('words.txt')
words = list(wordFile.read())
char = set(words)
chars = list(char)
chars.remove('\n')
for char in chars:
  count = words.count(char)
  if count > 1:
     print (char,'appears', count, 'time')

我希望上面的代码输出符号出现的次数,即使值为“1”。 以下是代码的当前输出:

8 appears 3 times
0 appears 3 times
1 appears 3 times
2 appears 2 times
3 appears 6 times
4 appears 2 times
7 appears 2 times
) appears 2 times
* appears 4 times
+ appears 2 times
- appears 2 times
# appears 8 times
% appears 4 times
& appears 7 times

然而,它缺少出现'1'时间的值(即'\') 这是存储在words.txt

中的内容
#+/084&"
#3*#%#+
8%203:
,1$&
!-*%
.#7&33&
#*#71%
&-&641'2
#))85
9&330*

所以只是为了澄清这一点,就是输出符号出现在文件中的频率。任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:3)

if count > 1:更改为if count > 0:

答案 1 :(得分:0)

with open('words.txt') as wordFile :
    words = list(wordFile.read())
    char = set(words)
    chars = list(char)
    chars.remove('\n')
    for char in chars:
      count = words.count(char)
      print (char,'appears', count, 'time')

如果要打印大于0的任何内容,根本不需要if

答案 2 :(得分:0)

return true回答了你的问题;

您可能需要使用collections.Counter来查找频率。

>>> import collections
>>> with open('words.txt') as f:
    words = list(f.read())


>>> count = collections.Counter(words)
>>> del count['\n']
>>> for c, n in count.items():
    print('{} appears {} times'.format(c, n))

! appears 1 times
# appears 8 times
" appears 1 times
% appears 4 times
$ appears 1 times
....