把单词“AND”和“OR”识别成一个字符串

2024-04-18 10:25:16 发布

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

假设我有这样一个字符串:

x = "Romeo and Juliet"

我想通过识别关键字“and”来区分“Romeo”和“Juliet”,例如创建一个输出列表:

y = ["Romeo", "Juliet"]

重要的是,不管“和”这个词是怎么写的(例如:和,和,和,等等),都不应该给口译员带来混淆,因为他们会理解“和”的意思,并且无论如何都会把这两个词分开。我用了一个可怕的解决方案:

y = []
i = 0
tmpString = ""
while x[i] != " ":
    tmpString = tmpString + x[i]
    i += 1

i += 1
if x[i:i+3] == 'and' or x[i:i+3] == 'aNd': #and all the other cases...
y.append(tmpString)
tmpString = ""
i += 4
while i < len(x):
    tmpString = tmpString + x[i] 
y.append(tmpString)

当然,我可以让算法更复杂一点(考虑到不止有两个名字的情况,当它是“or”而不是“and”等等),但是我不太喜欢在字符串中重复这么多次的想法。此外,我对Python非常陌生,不知道如何使用这些模块和方法,如“evaluate”或“parsing”等。 有没有人有任何建议,使一个更好,更灵活的算法?你知道吗


Tags: orand字符串算法列表if关键字解决方案
3条回答

可以使用正则表达式来实现这一点。举个例子:

>>> import re
>>> import string
>>> x = "Romeo and Juliet"
>>> map(string.strip, re.split(r"\bAND\b", x, flags=re.I))
['Romeo', 'Juliet']

尝试以下理解:

>>> x = "Romeo and Juliet"
>>> y = [word for word in x.split() if word.lower() != "and"]
>>> y
['Romeo', 'Juliet']
>>> x = "Romeo aND Juliet"
>>> y = [word for word in x.split() if word.lower() != "and"]
>>> y
['Romeo', 'Juliet']

当你把你的词和键比较时,键是应用lower()。这会将您可能发现的内容标准化为您所期望的形式。所以即使key = "aND"key = "AnD"key.lower() = "and"不管。你知道吗

为了完整起见,您可以使用lower()以外的函数来实现这一点,只要您的键匹配,就可以得到一个等价的解决方案。一些例子:

  • y = [word for word in x.split() if word.title() != "And"]

  • y = [word for word in x.split() if word.upper() != "AND"]

一些注意事项:

  • 正如Sunny Nada所指出的,如果名称有空格(x = "Joe Smith and Tom" >>> ["Joe", "Smith", "Tom"]),这种方法给出的结果就不太理想。如果这不是您想要的,您将需要一个更健壮的方法(比如re

  • 为了使您的方法有效,您可以将if x[i:i+3] == 'and' or x[i:i+3] == 'aNd':更改为if x[i:i+3] in ["and", "AND", "aNd", ...etc]:。这种方法通常被认为是测试多个值(or条件)的更好形式。或者,您可以使用我在理解中使用的if语句,得到类似的结果(if x[i:i+3].lower() == "and":

最后一个建议(主要是为了好玩),它可以处理多个单词的名称并避免re

>>> y = map(lambda s: s.strip(), map(lambda s: s.title(), x.lower().split('and')))
>>> y
['Romeo', 'Juliet']

请注意,这可能是对map()lambda函数的滥用

您可以使用^{}模块:

>>> import re
>>> re.split(r'\s+AND\s+', 'Romeo AnD Juliet', flags=re.I) # re.I tells Python to ignore case
['Romeo', 'Juliet']

如果要在AND或or上拆分,则可以稍微更改regexp:

>>> re.split(r'\s+(?:AND|OR)\s+', 'Romeo Or Juliet', flags=re.I)
['Romeo', 'Juliet']

相关问题 更多 >