Python - 查找在string1和string2中找到的字符数

时间:2014-08-01 01:51:06

标签: python

我试图找到第一个字符串中也在第二个字符串中找到的字符数。这就是我到目前为止所做的:

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()

我在def count()上遇到麻烦。我不知道我怎么能算出text1和text2中有多少字母不会被重复。任何帮助表示赞赏!

5 个答案:

答案 0 :(得分:3)

使用set.intersection

(set(text1).intersection(item2))

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

intersection()将接受任何iterable作为参数。

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

答案 1 :(得分: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

由于我们只考虑itext2的第一次出现,我们可以检查它是否存在于text2中,就像这样

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

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

答案 2 :(得分: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 :(得分:0)

您可以通过交叉字符串(获取2个字符串中的唯一字符)并获取结果的长度来完成此操作。像这样:

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)而不只是在你的print语句中调用,否则它不会调用函数)

答案 4 :(得分: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)
相关问题