gpt4 book ai didi

python - 正在从 myFile 中删除\n

转载 作者:太空宇宙 更新时间:2023-11-03 18:08:26 25 4
gpt4 key购买 nike

我正在尝试创建一个列表字典,其键是字谜词,值(列表)包含该字谜词中所有可能的单词。

所以我的字典应该包含这样的内容

{'aaelnprt': ['parental', 'paternal', 'prenatal'], ailrv': ['rival']} 

可能的单词位于 .txt 文件内。每个单词都用换行符分隔。示例

Sad
Dad
Fruit
Pizza

当我尝试编码时,这会导致问题。

with open ("word_list.txt") as myFile:
for word in myFile:
if word[0] == "v": ##Interested in only word starting with "v"
word_sorted = ''.join(sorted(word)) ##Get the anagram
for keys in list(dictonary.keys()):
if keys == word_sorted: ##Heres the problem, it doesn't get inside here as theres extra characters in <word_sorted> possible "\n" due to the linebreak of myfi
print(word_sorted)
dictonary[word_sorted].append(word)

最佳答案

如果“word_list.txt”中的每个单词后面都跟有“\n”,那么您可以使用切片来删除该单词的最后一个字符。

word_sorted = ''.join(sorted(word[:-1])) 

但是,如果“word_list.txt”中的最后一个单词不是后跟“\n”,那么您应该使用rstrip()

word_sorted = ''.join(sorted(word.rstrip())) 

切片方法的效率稍高,但对于此应用程序,我怀疑您会注意到其中的差异,因此您不妨谨慎行事并使用 rstrip()

关于python - 正在从 myFile 中删除\n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26419695/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com