Python - 查找字符串1和字符串2中共同的字符数量

1 投票
5 回答
1436 浏览
提问于 2025-04-18 15:35

我正在尝试找出第一个字符串中有多少个字符也出现在第二个字符串中。到目前为止,我的代码是这样的:

def main():
    text1 = raw_input("Enter word 1: ")
    text2 = raw_input("Enter word 2: ")

    print("The number of characters that occur in both", text1, "and", text2, "is", count)

def count(text1, text2):
    char = 0
    for i in text1:
        for j in text2:
            if i == j:
                char += 1

    return char

main()

我在定义 count() 这个函数时遇到了问题。我不太确定怎么才能计算出 text1 和 text2 中出现的字母数量,而且这些字母不能重复。任何帮助都非常感谢!

5 个回答

0

我不确定这是不是你想要的,但如果你需要把text1和text2中的字母总数加起来,并打印出结果,那是非常简单的。请看下面的代码:

text1 = raw_input("Enter word 1: ")
text2 = raw_input("Enter word 2: ")

x = len(text1) + len(text2)

print "The number of characters that occur in both text1 and text2 is " + str(x)
0

你可以通过找出两个字符串中共同的字符(也就是两个字符串里都有的独特字符)来实现这个功能,然后计算这些共同字符的数量。可以这样做:

def strIntersection(s1, s2):
   out = ""
   for c in s1:
     if c in s2 and not c in out:
       out += c
   return out



>>> strIntersection('asdfasdfasfd' , 'qazwsxedc')
'asd'

然后

len(strIntersection('asdfasdfasfd' , 'qazwsxedc'))
3

可以作为你的计数函数。

(另外,你在打印的时候需要调用 count(text1, text2),而不是只写 conut,这样才能正确调用这个函数)

0

这时候用一个 set(集合)会非常合适,因为它可以自动去掉重复的东西,而且查找速度很快。

def count(text1, text2):
  numchars = 0
  text1 = set(list(text1))
  text2 = set(list(text2))
  for char in text1:
    if char in text2:
      numchars += 1

  return numchars

把一个字符串先转换成列表,然后再转换成集合,这样就能去掉字符串中的所有重复字符(不过这个操作只在函数内部进行,原来的字符串还是好的)。接着,你可以检查第一个集合里的每个字符,看它是否在第二个集合里,这个检查是非常快的。

还有一点:如果你不想把大写的 A 和小写的 a 当作两个不同的字符来处理,可以用 text1 = set(list(text1.lower())) 来替代。

另外,你调用函数的方式不对。应该用 count(text1,text2),而不是单单用 count。如果你想把结果打印出来,还需要用 str(count(text1,text2)),因为 count() 函数返回的是一个整数,而你不能直接把它和字符串拼接在一起。

3

使用 set.intersection 方法:

(set(text1).intersection(item2))

In [22]: len(set("bana").intersection("banana"))
Out[22]: 3

intersection() 方法可以接受任何可迭代的对象作为参数。

def count(text1, text2):
    return len(set(text1).intersection(text2))
In [24]: count("foo","foobar")
Out[24]: 2

如果你想要重复的元素:

def count(text1, text2):
    s = set(text2)
    return len([x for x in text1 if  x in s])
In [29]: count("foo","foobar")
Out[29]: 3

In [30]: count("bana","banana")
Out[30]: 4
2

主要的问题是,你并没有调用 count 函数,而是直接打印了 count 函数这个对象。正确的做法应该是

print("The number of....", text2, "is", count(text1, text2))

另外,如果在第二个字符串中找到了字母,你需要增加计数器,然后可以跳到第一个字符串中的下一个字符。所以,你可以像这样跳出循环

for i in text1:
    for j in text2:
        if i == j:
            char += 1
            break

因为我们只考虑 text2i 的第一次出现,所以我们可以检查它是否存在于 text2 中,像这样

for i in text1:
    if i in text2:
        char += 1

但要记住,它不会考虑原始字符串中的重复项。例如,aaaa 会导致计数为 3

撰写回答