给出了如下所示的文本文件:
Samsung Galaxy S6 active SM-G890A 32GB Camo White (AT&T) *AS-IS* Cracked Screen
Samsung Galaxy S6 SM-G920 - 32GB - White Verizon Cracked screen
Samsung Galaxy S6 edge as is cracked screen我试着想出许多不同的方法来使字符串Samsung Galaxy S6与Samsung Galaxy S6 edge不匹配,但似乎无法想出一种可行的方法。在字符串中,很明显,电话的名称已经结束,外来的信息也开始了,这样就没有意义了,所以用这种方式将它们分开并与字典或类似的东西进行比较是行不通的。
我试着想出一些方法来写以下文章:
phones = ['Samsung Galaxy S6', 'Samsung Galaxy S6 Edge']
lines = open('phones.txt', 'r').readlines()
for line in lines:
for phone in phones:
if phone in line and no other phone in phones is in line:
print('match found')但我想不出构造它的正确方法有人有什么想法吗?我肯定我错过了一些简单的东西,但我不知道是什么。
发布于 2016-11-18 20:21:09
从整理你的手机开始,这样它就能看到它们的长度。
phones.sort(key=len,reverse=True) 那当你找到匹配的时候就中断
for phone in phones:
if phone in line:
print "FOUND:",repr(phone),"IN",repr(line)
break # we dont need to keep looking for other phones in this line也许吧?
这种方式“三星银河s6边缘”在您的支票中“三星银河”之前,您将匹配最长的.不需要对你的电话列表有更多的了解,比如regex回答
发布于 2016-11-18 20:22:10
发布于 2016-11-18 20:24:27
if sum(1 for phone in phones if phone in line) == 1:这实际上包括phones的成员,这些成员也是line的成员。然后我们检查一下,以确保号码是一个。
https://stackoverflow.com/questions/40685296
复制相似问题