如何使我的Python字符串不牢固地匹配?

2024-05-16 01:15:00 发布

您现在位置:Python中文网/ 问答频道 /正文

给定一个如下所示的文本文件:

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 S6Samsung 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')

但我想不出正确的方法来构建它-有人有什么想法吗?我肯定我错过了一些简单的东西,但就是想不出是什么


Tags: 方法字符串inislinephonescreengalaxy
3条回答
if sum(1 for phone in phones if phone in line) == 1:

这实际上统计了phones的成员,这些成员也是line的成员。然后我们检查一下,确定号码是1

首先对你的手机进行分类,这样它就能按长度查看它们

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

也许吧

这样一来,“三星Galaxy s6 Edge”就排在“三星Galaxy”之前了,您将匹配最长的一款。。。不需要像regex答案那样对你的电话列表有更多的了解

消极的展望会:

Samsung Galaxy S6(?! edge)

a demo on regex101.com

相关问题 更多 >