我想得到给定句子中的每个字符数。我尝试了下面的代码,我得到了每个字符的计数,但它显示输出中重复的字符数。如何删除重复的字符。
def countwords(x):
x=x.lower()
for i in x:
print(i,'in',x.count(i))
x=str(input("Enter a paragraph "))
countwords(x)
我的输出是:
我的输出不应包含空格数和重复的字符..怎么办...... !!!
答案 0 :(得分:1)
检查此代码:
my_string = "count a character occurance"
my_list = list(my_string)
print (my_list)
get_unique_char = set(my_list)
print (get_unique_char)
for key in get_unique_char:
print (key, my_string.count(key))
答案 1 :(得分:1)
有一些不同的方法,大多数是jonrsharpe的评论所暗示的,但我建议一个简单的set
。
下面列出了设定的方法以及其他一些方法:
# An approach using a set
def countwords_set(s):
for c in set(s):
if c == ' ': continue
print(c, 'in', s.count(c))
# An approach using a standard dict
def countwords_dict(s):
d = dict()
for c in s:
if c == ' ': continue # Skip spaces
d[c] = d.get(c,0) + 1 # Use the .get method in case the
# key isn't set
for c,x in d.items(): # Display results
print(c, 'in', x)
# An approach using a defaultdict (from the collections module)
def countwords_ddict(s):
from collections import defaultdict # Typically, imports go at the top
d = defaultdict(int)
for c in s:
if c == ' ': continue
d[c] += 1
for c,x in d.items():
print(c, 'in', x)
# An approach using a Counter (from the collections module)
def countwords_counter(s):
from collections import Counter # Typically, imports go at the top
counter = Counter(s)
# Counters can be accessed like dicts
for c,x in counter.items():
if c == ' ': continue
print(c, 'in', x)
# User input and comparison
s = str(input("Enter a paragraph "))
s = s.lower()
countwords_set(s)
print("---")
countwords_dict(s)
print("---")
countwords_ddict(s)
print("---")
countwords_counter(s)
print("---")
对于每种方法,输出基本相同,尽管字典的顺序可能不同,因为Python字典是无序的。
答案 2 :(得分:0)
使用词典。
def countwords(x):
d = dict()
x=x.lower()
for i in x:
if i in d.keys():
d[i] = d[i] +1;
else:
d[i] = 1;
for i in d.keys():
print i + " " + d[i]