[英]Python - Finding specific string [At least 2 words]
Another question from total Python newbie. 来自Python新手的另一个问题。
I have an array, user can input 5 different words/sentences, after user enters those 5, user enters one of the 5 texts again and program removes this string from array, than user adds another string and it appends directly to the Index = 0. 我有一个数组,用户可以输入5个不同的单词/句子,在用户输入了5个单词/句子之后,用户再次输入5个文本之一,然后程序从数组中删除该字符串,而不是用户添加另一个字符串并将其直接附加到Index = 0 。
But the problem begins when i want to run over this array and find if any of the strings in the array have at least 2 words. 但是问题开始于当我想在此数组上运行并查找数组中的任何字符串是否至少有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])
Output : 输出:
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 . . .
So, my code doesn't do anything, i need to somehow find if any of the strings have at least 2 words and print all of those words. 因此,我的代码没有执行任何操作,我需要以某种方式查找是否任何字符串中至少有2个单词并打印所有这些单词。
for s in Text:
if s.isspace():
print(Text[s])
In the code above, s is the full string for example in your example s could be 'CD' and this string is not a space. 在上面的代码中,s是完整字符串,例如,在您的示例中s可能是“ CD”,并且该字符串不是空格。
To check if s has two or more words you can use .split(' ') but before that you have to .strip() your string to delete spaces from borders. 要检查s是否有两个或两个以上的单词,可以使用.split(''),但在此之前,您必须先.strip()字符串以删除边框中的空格。
s = 'Hello World '
print(s.strip().split(' '))
>>> ['Hello', 'World']
In the example above, s has two spaces, so strip delete the last space because is a border space and then split gives you a list of string that are separate by spaces. 在上面的示例中,s有两个空格,因此带删除最后一个空格,因为它是一个边界空格,然后进行分割将为您提供一个由空格分隔的字符串列表。
So the solution to your problem could be 因此,解决您的问题的方法可能是
for s in Text:
if len(s.strip().split(' ')) > 1:
print(s.strip().split(' '))
So, my code doesn't do anything, i need to somehow find if any of the strings have at least 2 words and print all of those words. 因此,我的代码没有执行任何操作,我需要以某种方式查找是否任何字符串中至少有2个单词并打印所有这些单词。
Perhaps loop through the list and split each string. 也许遍历列表并拆分每个字符串。 Then determine if the resulting sum is greater than 1: 然后确定结果总和是否大于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])
Using list comprehension: 使用列表理解:
x = [w for w in text_list if len(w.split(' ')) > 1]
print(x)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.