常用字符搜索找不到“?”的用法在列表中

Common character search can't find usages of "?" in list

我正在计算字符串中的字符以及列表中每个单词之间常用的字符,出于某种原因,当像“?”这样的字符时会导致错误。被扔进一个词或作为它自己的字符串。我有两种不同的方法,计数器似乎识别“?”但另一个出于某种原因没有?提前感谢您的帮助,我确定这是我遗漏的东西,但我不明白为什么它会给我一个错误而不是另一个错误。

如果可能的话,我希望使用第二种方法而不是 Counter 方法

Name = ["Adam","Max","Mike","Ted","Liam","Daniel"]


#You can see that the above list will work with both methods but for some reason adding a "?" to either causes issues and errors
def listToString(s):
        str1 = " "

        return (str1.join(s))
s = Name
stringOfList =(listToString(s))




from collections import Counter

s1 = stringOfList.lower()

commonLetters = Counter(s1)
print(commonLetters)








import re


test1 = s1
test2 = test1

common = {}

if len(test1) < len(test2):
        for character in test1:
                if character in test2:
                        common[character] = len(re.findall(character, test2))

else:
        for character in test2:
                if character in test1:
                        common[character] = len(re.findall(character, test1))
for word, count in common.items():
        print("\nThe words contains these common characters" +" {1}\t{0}".format(word,count))

? 是 python 正则表达式中的 special character。如果你想使用第二种方法(使用 re.findall)你想转义?通过在正则表达式 findall 方法中使用 \? 来查找字符文字 ?.

的所有实例

例如,

re.findall("?", "?") 不会工作

re.findall("\?", "?")

尝试更多类似的东西。


from collections import Counter
Name = ["Adam","Max","Mike","Ted","Liam","Daniel?"]
stringOfList = ' '.join(Name)
s1 = stringOfList.lower()
commonLetters = Counter(s1)
for letters in commonLetters:
    print(f"letters count of {letters} is {commonLetters[letters]}")