[英](Python) How do I compare a few letters to a whole list of words to find, what words contain the searched-for letters in order?
Question says it all basically.问题基本上说明了一切。
I'm trying to find words that contain specific letters in order.我试图按顺序查找包含特定字母的单词。 So if I search for "ers" it should only give out words like "ERStaunding", etc.
因此,如果我搜索“ers”,它应该只会给出“ERStaunding”等词。
That's what I have so far: (doesn't work because a string requires a string as left operand) but you get the idea:这就是我到目前为止所拥有的:(不起作用,因为字符串需要一个字符串作为左操作数)但你明白了:
sorted = []
for i in range(0,len(words)): #"words" is a list of 1600 words
if possible in words[i]: #error because of what I said before
sorted.append(words[i]) #"possible" is a string of letters
print(sorted)
thanks in advance!提前致谢!
edit:编辑:
This is what I put in/what comes out: (in pseudocode, it's hangman for uni)这是我输入的内容/输出的内容:(在伪代码中,它是 uni 的刽子手)
user input: "hello" - word to be guessed用户输入:“你好”——要猜的词
cpu guesses: "h" (for example) "is h part of your word? (y/n)" cpu 猜测:“h”(例如)“h 是你单词的一部分吗?(y/n)”
user input: "y"用户输入:“y”
computer knows that "h" is at position 1 (by comparing to the word that has to be guessed) - stupid, I know but this is an example:D: h _ _ _ _计算机知道“h”位于 position 1(通过与必须猜测的单词进行比较)-愚蠢,我知道,但这是一个例子:D:h _ _ _
now the pc should compare what he has (h up to this point at index 0) to words in a database (in my case words.txt) and only leave the ones that have "h" as their first letter.现在电脑应该将他所拥有的(h 到索引 0 处的这一点)与数据库中的单词(在我的例子中是 words.txt)进行比较,并且只留下首字母为“h”的单词。 This process should be interchangeable.
这个过程应该是可以互换的。 For example: if the pc has _ _ ll _, he should still be able to filter the words.
例如:如果 pc 有_ _ ll _,他应该仍然可以过滤单词。
I hope that's what you meant with an example, hope this helps:D我希望这就是您举个例子的意思,希望对您有所帮助:D
This gives only words that contain possible
:这仅给出包含
possible
单词:
words = ["test", "list", "here"] #list of words
possible = "st" #string to find within each word
sortedList = [] #output list defined
for word in words: #for each word
if possible.lower() in word.lower(): #if the word includes the string
sortedList.append(word) #add the word to the output
print(sortedList) #print output
Output: Output:
['test', 'list']
I think you just want to check whether the given word is present at the begining.我想你只是想检查给定的单词是否在开头出现。
substring=substring.lower()
for i in range(0,len(words)): #"words" is a list of 1600 words
s=words[i].lower()
if substring in s: # word found at the begining
sorted.append(words[i])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.