Python-检查字母是否出现在连续的单词中

Python-检查字母是否出现在连续的单词中,python,regex,list,Python,Regex,List,我有一个任务,我需要阅读输入并检查输入是否出现在某些单词中。例如: Who are your friends? Fred Bill Sue Simone What is the message? Should you make tea? Sue could have written this. 它打印“Sue可能写了这封信,因为字母“S”、“U”和“E”出现在每个连续的单词中。另一个例子是: Who are your friends? James Nicky Jake What is the

我有一个任务,我需要阅读输入并检查输入是否出现在某些单词中。例如:

Who are your friends? Fred Bill Sue Simone
What is the message? Should you make tea?
Sue could have written this.
它打印“Sue可能写了这封信,因为字母“S”、“U”和“E”出现在每个连续的单词中。另一个例子是:

Who are your friends? James Nicky Jake
What is the message? join and make enough cash today!
James could have written this.
Jake could have written this.
这两个名字都是打印出来的,因为它们的两个字母在每个单词中连续出现。我有以下代码:

friends = input("Who are your friends? ").split()
message = input("What is the message? ").split()

name = []
other = []

for friend in friends:
  for f in friend.lower():
    for word in message:
      print("checking if", f, "is in", word.lower())
      if f in word.lower():
        print("Adding", f, " to name list")
        name.append(f)
        break
      else:
        other.append(f)
        continue

joinedResult = ''.join(name)

for person in friends:
  if person.lower() in joinedResult:
    print(person, "could have written this.")
它适用于第一个示例,但对于第二个示例,它会打印所有三个名称:

James could have written this.
Nicky could have written this.
Jake could have written this.
我了解到,代码不会检查名称中的字母是否连续出现,而是检查名称是否在任何单词中。我如何解决这个问题

friends=["James","Nicky","Jake"]
words=["James could have written this","Jake could have written this"]
for friend in friends:
    for word in words:
        for name in word.split():
            if friend.lower()==name.lower():
                print friend,"yes"
            else:
                print friend,"no"

你可以使用这个简单的代码,而不是用
字母来比较
字母
,这也容易出错,因为字母可以是字符串中的任意位置,但不一定是连续的。

请注意,据我所知,你的意思是他们名字中的第n个字母必须出现在消息中的第n个单词中。也许我错了,你可以澄清一下通知

您需要将姓名中的每个字母与邮件中的一个单词配对,然后检查是否包含。您可以使用
zip

friends = 'James Nicky Jake'.split()
message = 'join and make enough cash today!'.split()

names = []
others = []

for friend in friends:
    match = True
    length = len(friend)

    for letter, word in zip(friend.lower(), message):
        if not letter in word.lower():
            match = False
            break

    if match:
        names.append(friend)
    else:
        others.append(friend)

for person in names:
        print(person, "could have written this.")
产出:

James could have written join and make enough cash today!
Jake could have written join and make enough cash today!
Sue could have written Should you make tea?
Bob could have written Bob constructed Balloon Town
现在完全重新做,干净多了

大部分工作是在find_char函数中完成的,它是一个生成器,在每次迭代中减少了搜索空间,因此它不会在序列中找到[0,1,0]位置“Bob”,而是[0,1,2]


任何问题,请随时提问。

使用正则表达式可能会更容易一些:

friends = raw_input("Who are your friends? ").split()
message = raw_input("What is the message? ").lower()

name = []
other = []

for friend in friends:
    regStr = '\w*\s?' + ''.join(['\w*' + f + '\w*\s' for f in friend.lower()])
    if re.match(regStr, message):
        name.append(friend)

for friend in name:
    print friend + " could have written this."
正则表达式模式类似于:
\w*\s?(s)\w*\s\w*(u)\w*\s\w*(e)\w*
for friend
Sue

测试用例:

Shoulde i?
[无匹配](sue找到但不连续=>
[S]ho[u]ld[e]i?

我应该泡茶吗?
[不匹配]

你应该泡茶吗?
[sue]

你可以使用和:

代码 输出 评论 函数返回一个好名字的列表,这些人可能写了包含他们名字的首字母缩略词,所以

  • 我们开始将列表初始化为空列表
接下来,我们观察到,消息中超过字数的名称不能满足要求,因此,稍后使用它

  • 我们计算并保存消息的长度(大写)
现在,

  • 我们循环查看列表
    名称
    ,以验证
    名称
    是否符合规则

    • 如果名称太长,则无需进一步处理

    • 使用
      zip
      ,我们构建了一个成对的列表,
      name
      中的字符
      c
      message
      中的
      word
      ,我们使用列表理解构建了一个布尔值列表

    • 如果
      all
      布尔值为true(
      all
      any
      是有用的内置项!),则将
      名称
      附加到
      好名称列表中

  • 将好名字列表返回给呼叫者

我还包括了几个模仿OP示例的函数调用

可能是期待已久的一艘班轮
s
是为嫌疑犯准备的


def s(n,m):如果len(g),则返回[g代表l英寸[len(m)]代表g英寸n输入的意思是:立即加入并赚取足够的现金!。如果我用输入替换您存储在Word中的内容,它将不起作用。@user3036519将您的输入转换为我使用的格式。然后使用代码。我想您误解了OP的目的。据我所知,如果他们名字中的第n个字母出现在消息中的第n个单词(所有n个)。如果在
join
之前有另一个单词,那么第二个示例的输出是什么,比如说:“zzz”?如果friends=“Fred Bill Sue Simone”和消息=“你应该泡茶吗?”?“输出是:Bill本可以写这个Sue本可以写这个。所需输出:Sue本可以写这个忘记检查输入中是否有姓名的字母。请稍候,将修复此问题。我收到了一个语法错误,用于if sorted(sequence\u check)==sequence\u check”“。join(字母)=friend.lower():.Near”“。join(字母)在python 3.x.xIf friends=“Anastasia”和message=“在另一个故事中,蚂蚁激活了超级离子!”)中,使用next(gen)而不是gen.next()。输出是:Anastasia可以编写这个。程序不应该输出任何内容,因为“Anastasia”不会出现在所有单词中。如果friends=“Anastasia”和message=“在另一个故事中,蚂蚁激活了超级离子!”。输出是:Anastasia可能编写了这个。程序不应该输出任何东西,因为“Anastasia”并没有出现在所有的单词中。@user3036519我明白你的意思,在这种情况下
zip()
还不够,请选择
itertools.zip\u longest
.friend=bob和message=bob。您的代码不输出任何内容,它本来是要输出的:bob可以编写this@user3036519现在呢?很好,但有一种情况是它不起作用:说消息中的第一个单词与任何消息中的任何第一个字母都不匹配在你的第二个例子中,你的名字是:“dummyword加入,今天赚足够的钱!”
friends = raw_input("Who are your friends? ").split()
message = raw_input("What is the message? ").lower()

name = []
other = []

for friend in friends:
    regStr = '\w*\s?' + ''.join(['\w*' + f + '\w*\s' for f in friend.lower()])
    if re.match(regStr, message):
        name.append(friend)

for friend in name:
    print friend + " could have written this."
friends = input("Who are your friends? ").split()
message = input("What is the message? ").lower().split()

for friend in friends:
  if len(friend) <= len(message):
    if all(x in y for x, y in zip(friend.lower(), message)):
        print(friend, "could have written this.")
>>> 
Who are your friends? Fred Bill Sue Simone
What is the message? Should you make tea?
Sue could have written this.
>>> 
Who are your friends? James Nicky Jake
What is the message? join and make enough cash today!
James could have written this.
Jake could have written this.
def whosdoneit(names,message):
    good_names = []
    l_m = len(message)
    for name in names:
        if len(name) > l_m: continue
        if all(c.lower() in word.lower() for c, word in zip(name, message)):
            good_names.append(name)
    return good_names

print whosdoneit('Fred Bill Sue Simone'.split(),
                 'Should you make tea?'.split())

print whosdoneit('James Nicky Jake'.split(),
                 'join and make enough cash today!'.split())
['Sue']
['James', 'Jake']
def s(n,m):return [g for l in [len(m)] for g in n if len(g)<=l and all([c.lower() in w.lower() for c,w in zip(g,m)])]