簡體   English   中英

Python-查找特定的字符串[至少2個字]

[英]Python - Finding specific string [At least 2 words]

來自Python新手的另一個問題。

我有一個數組,用戶可以輸入5個不同的單詞/句子,在用戶輸入了5個單詞/句子之后,用戶再次輸入5個文本之一,然后程序從數組中刪除該字符串,而不是用戶添加另一個字符串並將其直接附加到Index = 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: CD ['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個單詞並打印所有這些單詞。

for s in Text:
if s.isspace():
    print(Text[s])

在上面的代碼中,s是完整字符串,例如,在您的示例中s可能是“ CD”,並且該字符串不是空格。

要檢查s是否有兩個或兩個以上的單詞,可以使用.split(''),但在此之前,您必須先.strip()字符串以刪除邊框中的空格。

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

在上面的示例中,s有兩個空格,因此帶刪除最后一個空格,因為它是一個邊界空格,然后進行分割將為您提供一個由空格分隔的字符串列表。

因此,解決您的問題的方法可能是

for s in Text:
    if len(s.strip().split(' ')) > 1:
        print(s.strip().split(' '))

因此,我的代碼沒有執行任何操作,我需要以某種方式查找是否任何字符串中至少有2個單詞並打印所有這些單詞。

也許遍歷列表並拆分每個字符串。 然后確定結果總和是否大於1:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM