函数无法识别两个列表中的相似性的问题

时间:2019-05-02 10:58:18

标签: python-3.x

我正在尝试编写一段代码,如果在两个列表之间发现相似之处,它将打印出一些内容,以便以后可以将其实现为句子拆分器。但是我在分析一个列表以查看它是否包含另一个列表的元素时遇到困难。

下面的代码显示了我目前正在尝试的内容:

    sentence= "Hello. My name is George... Michael! David Browns. alittlemouse"
    exception_1_3_char = [". a", ". b", ". c", ". d", ". e", ". f", ". g", ". h", ". i", ". j", ". k", ". l", ". m", ". n", ". o", ". p", ". q", ". r", ". s", ". t", ". u", ". v", ". w", ". x", ". y", ". z"]
    def exception_finder(target_sentence):
        target_sentence = list(target_sentence)
        for character in range(len(exception_1_3_char)):
            if character in target_sentence:
                print("Exception Found")
    exception_finder(sentence)

当前结果:

完全没有输出。

所需结果:

    Exception Found

3 个答案:

答案 0 :(得分:0)

我想你想要这个:

for segment in exception_1_3:
    if segment in sentence:
       print("Exception found")

答案 1 :(得分:0)

您不想将sentence变成一个列表,而只想遍历exception_1_3_char中的字符(您对range(len())所做的工作是遍历0, 1, ..., 25 )。

sentence= "Hello. My name is George... Michael! David Browns. alittlemouse"
exception_1_3_char = [". a", ". b", ". c", ". d", ". e", ". f", ". g", ". h", ". i", ". j", ". k", ". l", ". m", ". n", ". o", ". p", ". q", ". r", ". s", ". t", ". u", ". v", ". w", ". x", ". y", ". z"]
def exception_finder(target_sentence):
    for character in exception_1_3_char:
        if character in target_sentence:
            print("Exception Found")
exception_finder(sentence)

答案 2 :(得分:0)

根据您的问题,您似乎正在尝试在某种类型的输入(例如字符串)中找到标准模式。建议不要使用正则表达式。而不是在exception_1_3_char中使用一长串字符。

此答案使用您的原始句子,并使用正则表达式查找模式(一个句点,后跟空白,再一个小写字符)。

import re 

sentence = "Hello. My name is George... Michael! David Browns. alittlemouse"

def exception_finder(target_sentence):
  exception_character_pattern = re.compile(r'\.\s[a-z]{1}')
  results = exception_character_pattern.findall(target_sentence)
  if results:
     print("Exception Found")
     # results is a list of the exception characters found
     # in the target_sentence
     print (results)
     # outputs
     ['. a']

exception_finder(sentence)

除了我使用列表推导,该答案与上一个答案相似,因为您提到输入是列表。

import re

# I turned your original string into a list and modified one of the characters.
sentence = ["Hello. my name is George... Michael! David Browns. alittlemouse"]

def exception_finder(target_list):
  exception_character_pattern = re.compile(r'\.\s[a-z]{1}')
  results = [match for match in (exception_character_pattern.findall(line) for line in target_list) if match]
  if results:
     print("Exception Found")
     # results is a list of the exception characters found
     # in the target_sentence
     print (results)
     # outputs
     [['. m', '. a']]

exception_finder(sentence)