代码之家  ›  专栏  ›  技术社区  ›  ლუკა ჩიტიშვილი

Python-查找特定字符串[至少2个单词]

  •  0
  • ლუკა ჩიტიშვილი  · 技术社区  · 7 年前

    另一个来自Python新手的问题。

    我有一个数组,用户可以输入5个不同的单词/句子,在用户输入这5个单词/句子后,用户再次输入5个文本中的一个,程序从数组中删除这个字符串,然后用户添加另一个字符串,它直接附加到索引=0。

    但当我想遍历这个数组并找出数组中是否有任何字符串至少有2个单词时,问题就开始了。

    Text = []
    for i in range(0, 5):
        Text.append(input('Enter the text: '))
    
        print (Text)
    for i in range(0, 1):
        Text.remove(input('Enter one of the texts you entered before: '))
        print (Text)
    
    for i in range(0, 1):
        Text.insert(0,input('Enter Some Text: '))
        print (Text)
    
    for s in Text:
        if s.isspace():
            print(Text[s])
    

    输出:

    Enter the text: A
    ['A']
    Enter the text: B
    ['A', 'B']
    Enter the text: C D
    ['A', 'B', 'C D']
    Enter the text: E
    ['A', 'B', 'C D', 'E']
    Enter the text: F
    ['A', 'B', 'C D', 'E', 'F']
    Enter one of the texts you entered before: F
    ['A', 'B', 'C D', 'E']
    Enter Some Text: G
    ['G', 'A', 'B', 'C D', 'E']
    Press any key to continue . . .
    

    所以,我的代码什么都不做,我需要以某种方式找到任何字符串是否至少有2个单词,并打印所有这些单词。

    2 回复  |  直到 7 年前
        1
  •  1
  •   Martin Rodriguez    7 年前
    for s in Text:
    if s.isspace():
        print(Text[s])
    

    检查s是否有两个或更多可以使用的单词。拆分(“”),但在此之前,您必须。strip()删除字符串中的空格。

    s = 'Hello World '
    print(s.strip().split(' '))
    >>> ['Hello', 'World']
    

    在上面的示例中,s有两个空格,因此strip删除最后一个空格,因为它是一个边界空间,然后split将提供一个由空格分隔的字符串列表。

    所以你的问题的解决方案可能是

    for s in Text:
        if len(s.strip().split(' ')) > 1:
            print(s.strip().split(' '))
    
        2
  •  0
  •   AndrosJendi    7 年前

    所以,我的代码没有任何作用,我需要以某种方式找到 字符串至少有2个单词,并打印所有这些单词。

    text_list = ['G', 'A', 'B', 'C D', 'E']
    
    for i in range(len(text_list)):
        if len(text_list[i].split(' ')) > 1:
            print(text_list[i])
    

    使用列表理解:

    x = [w for w in text_list if len(w.split(' ')) > 1]
    print(x)