python - 我可以用这些字符组成什么词?
问题描述
我有一个问题,如果我有一个包含 16 个字符的列表和一个包含 words 的 txt,我怎么知道这 16 个字符可以组成哪些单词?
重要:(不再重复)
例如:“smalu”
无法形成“小”字,因为缺少“L”
f = open ("twl06.txt", "r")
wordlist = ("a", "b", "c", "a", "r", "h", "k", "c", "i", "p", "h", "t", "r", "h", "k", "c")
while (True):
line = f.readline () #For example "small"
line2 = list(line)
if line2 in wordlist: #Check if the word in line can be created with the characters that Wordlist has
print (line) #Print the word that can be created
print ("index of elements:" How do I do this?) #Print the index (in wordlist) of each character found
解决方案
虽然,就像说的那样,我们不是代码编写或教程服务,但如果您想实现这一点,您可以执行以下操作:
wordlist = ["a", "b", "c", "a", "r", "h", "k", "c", "i", "p", "h", "t", "r", "h", "k", "c"]
words = open("twl06.txt", "r").read().split() #Get all words in a text file
for word in words: #Cycle through all words
indexes = [] #Set indexes to be blank
usedletters = [] #Set used letters to blank
for letter in word: #Cycle through each letter in the words
if letter in wordlist: #Check if litter is in the list of words
indexes.append(wordlist.index(letter)) #Append the index of the letter to our list
usedletters.append(letter)
wordlist[wordlist.index(letter)] = 0 #Set curreent used letter to placeholder
if len(indexes) == len(word): #Check if we found all the letters
print(word) #print the word that was found
print("index of elements:", indexes) #print the list of that words indexes
else: #In case we didnt get all the letters
for i in range(len(indexes)): #Cycle through all replaced indexes
wordlist[indexes[i]] = usedletters[i] #Set them back to their original letters
推荐阅读
- react-native - 为什么 KeyboardAvoidingView 没有出现在 React Native App 中?
- excel - VBA - 比较列和一个目标单元格之间的绝对差异
- python - 如何使用 MultiIndex 数据框加入多个时间序列?
- python - 如何在 Python 中连接到需要我登录并拥有自签名证书的站点?
- file-upload - 如何开玩笑地模拟文件上传或文件对象?
- collections - 如何在具有相同键的哈希图中添加值以及何时将值存储为另一个哈希图
- java - 如何将txt文件放到第二个txt文件的特定行
- mysql - MYSQL 案例何时
- python-3.x - 如何在真正的智能手机上运行自动化测试?
- sql - SQL连接查询效率