我想获取给定句子中每个字符的数量。我尝试了下面的代码,我得到了每个字符的计数,但它在输出中显示了重复的字符计数。如何删除重复的字符。
def countwords(x):
x=x.lower()
for i in x:
print(i,'in',x.count(i))
x=str(input("Enter a paragraph "))
countwords(x)
我的输出是:
我的输出不应包含空格数和重复字符..该怎么办....!!!
检查此代码:
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))
有几种不同的方法,最有暗示的是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 字典是无序的。
使用字典。
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]
或者将 numpy 与此单行代码一起使用
np.unique(np.array(list('count these characters')), return_counts=True)
#Print the no of occurances of each char in a string including spaces and punctuations
text = "India won the ODI worldcup in the year 2011 !"
counter = dict()
for word in text:
for char in word:
count = text.count(char)
counter[char] = count
print(counter)
输出:{'I': 2, 'n': 3, 'd': 2, 'i': 2, 'a': 2, ' ': 9, 'w': 2, 'o': 2 、“t”:2、“h”:2、“e”:3、“O”:1、“D”:1、“r”:2、“l”:1、“c”:1、“ u': 1、'p': 1、'y': 1、'2': 1、'0': 1、'1': 2、'!': 1}