我正在尝试创建一个程序来计算字符串中字母的出现次数,但是我不知道如何在保留原始字母的情况下使其不区分大小写。
我尝试将每个项目分配给字典,其键为字符串中出现的次数,但是,例如,如果我说abA
,它将把A
和a
计为不同的字母。
import operator
def first_non_repeating_letter(string):
string = string.lower()
di = {}
for i in string:
di[i] = string.count(i)
if all(value > 1 for value in di.values()):
return ""
else:
var = min(di.items(), key=operator.itemgetter(1))[0]
return var
输出: 代替
output = {"a":1 , b:"1" , "A":1}
我想要:
output = {"A/a" : 2, "b":1}
并返回:the repeated letter is A or a
答案 0 :(得分:2)
这会将所有小写/大写字符及其计数合并到一个字典中:
from collections import Counter
from itertools import groupby
s = 'AbCxbaBc'
out = {}
for v, g in groupby(sorted(Counter(s).items(), key=lambda k: 2*ord(k[0].upper()) - k[0].islower()), lambda k: k[0].lower()):
l = [*g]
out[''.join(i[0] for i in l)] = sum(i[1] for i in l)
print(out)
# non repeated letters:
non_repeating = [k for k, v in out.items() if v==1]
print('Non repeated letters:', non_repeating)
# first non repeated letter:
if non_repeating:
m = min(map(lambda i: (s.index(i), i), non_repeating))
print('First non repeated letter:', m[-1])
else:
print('All letters are repeating!')
打印:
{'aA': 2, 'bB': 3, 'cC': 2, 'x': 1}
Non repeated letters: ['x']
First non repeated letter: x
答案 1 :(得分:2)
这应该可以满足您的需求。
import operator
def first_non_repeating_letter(string):
dict = {}
lowercase_string = string.lower()
# first we have to make a dictionary counting how many occurrences there are
for ch in lowercase_string:
if ch in dict:
dict[ch] = dict[ch] + 1
else:
dict[ch] = 1
# check if the number of occurrences is one, then return it
for ch in lowercase_string:
if ch in dict and dict[ch] == 1:
index = lowercase_string.find(ch)
return string[index]
示例:
输入:“ sTreSs”
输出:“ T”
答案 2 :(得分:1)
这可能会帮助
import collections
c = collections.Counter('PaRrOt'.lower())
sorted(c.items(), key=lambda c: c[0])
[('a', 1), ('o', 1), ('p', 1), ('r', 2), ('t', 1)]
来源 https://stackoverflow.com/a/22819467/5202279
编辑:基于OP的评论。
您可以简单地检查该特定字母的字典值是否为1,然后再重复一次。
至于字母的case_case。查看字母是否重复,然后使用正则表达式将其与原始字符串匹配。
答案 3 :(得分:1)
您总是可以创建一对映射:一个大小写折叠的字符到其计数,另一个到第一次出现的映射。
from collections import Counter
some_string = 'Some string'
lower_string = some_string.casefold()
count = Counter(lower_string)
firsts = dict(zip(lower_string, some_string))
现在,对于count
中的和字符,您可以在firsts
中查找其原始外观。