2012-03-16 75 views
0

问题:请勿在您的函数中使用set:使用列表返回第一个和最后一个名称中的常见字母列表(交叉点)提示用户名字和姓氏,并以名字和姓氏作为参数来调用函数并打印返回的列表。Python函数返回第一个和最后一个名字中的常见字母列表

我不明白为什么我的程序只是打印“不匹配”,即使有字母匹配。任何帮助!谢谢一堆!

到目前为止的代码:

import string 

def getCommonLetters(text1, text2): 
""" Take two strings and return a list of letters common to 
    both strings.""" 
    text1List = text1.split() 
    text2List = text2.split() 
    for i in range(0, len(text1List)): 
     text1List[i] = getCleanText(text1List[i]) 
    for i in range(0, len(text2List)): 
     text2List[i] = getCleanText(text2List[i]) 

    outList = [] 
    for letter in text1List: 
     if letter in text2List and letter not in outList: 
      outList.append(letter) 
    return outList 

def getCleanText(text): 
"""Return letter in lower case stripped of whitespace and 
punctuation characters""" 
    text = text.lower() 

    badCharacters = string.whitespace + string.punctuation 
    for character in badCharacters: 
     text = text.replace(character, "") 
    return text 

userText1 = raw_input("Enter your first name: ") 
userText2 = raw_input("Enter your last name: ") 
result  = getCommonLetters(userText1, userText2) 
numMatches = len(result) 
if numMatches == 0: 
    print "No matches." 
else: 
    print "Number of matches:", numMatches 

for letter in result: 
    print letter 
+0

的问题似乎是你Python语法... – JBernardo 2012-03-16 20:36:52

回答

2

试试这个:

def CommonLetters(s1, s2): 
    l1=list(''.join(s1.split())) 
    l2=list(''.join(s2.split())) 
    return [x for x in l1 if x in l2] 

print CommonLetters('Tom','Dom de Tommaso')  

输出:

>>> ['T', 'o', 'm'] 
+0

非常感谢你!这实际上救了我。我一直在解决这个问题几个小时。 – user1210588 2012-03-16 19:30:23

+2

没有必要将字符串转换为列表。字符串已经可迭代了。我甚至会跳过分裂,因为这不会删除标点符号,所以您仍然需要单独的过滤步骤。只是'def common_letters(s1,s2):如果s2中的x'返回[x对于s1中的x]'就是这样做的。 – agf 2012-03-16 20:18:05

+0

@Jernardo在问题中没有指定'set's。 – agf 2012-03-16 20:36:08

3
for letter in text1List: 

这是你的问题。 text1List是列表,而不是字符串。你迭代一个字符串列表(例如['Bobby','Tables']),然后检查'Bobby'是否在列表text2List中。

你想迭代你的字符串text1的每个字符,并检查它是否存在于字符串text2中。

你的代码中有一些非pythonic成语,但你会及时了解到。

后续行动:如果我用小写字母输入我的名字,用大写字母输入我的名字,会发生什么?你的代码会找到任何匹配吗?

+0

感谢编写Java!这帮助我指出了正确的方向。 – user1210588 2012-03-16 19:30:42

1

此前set()是重复去除常见的成语在Python 2.5,你可以使用一个列表的转换到字典中删除重复。

下面是一个例子:

def CommonLetters(s1, s2): 
    d={} 
    for l in s1: 
     if l in s2 and l.isalpha(): 
      d[l]=d.get(l,0)+1 
    return d        

print CommonLetters('matteo', 'dom de tommaso') 

这将打印像这样常见的字母数:

{'a': 1, 'e': 1, 'm': 1, 't': 2, 'o': 1} 

如果你想拥有的那些常用字母列表,只需要使用钥匙字典的()方法:

print CommonLetters('matteo', 'dom de tommaso').keys() 

哪个打印只是键:

['a', 'e', 'm', 't', 'o'] 

如果你想大小写字母相匹配,逻辑添加到该行:

if l in s2 and l.isalpha(): 
相关问题