こんにちは私は最近、Python 3で23005語を含むテキストファイルを読み込むプログラムを作成しようとしていますが、ユーザーは文字列9文字のを入力し、単語を作成して比較しますテキストファイル内のもの。リストの文字のみを印刷するにはどうすればいいですか?
私は4-9文字の間に、リストの真ん中にある文字を含む単語を印刷したいと考えています。例えば、ユーザが文字列「anitsksem」を入力すると、5番目の文字「s」がその単語に存在しなければならない。ここで
は、私は自分で得ているどのくらいです:
# Open selected file & read
filen = open("svenskaOrdUTF-8.txt", "r")
# Read all rows and store them in a list
wordList = filen.readlines()
# Close File
filen.close()
# letterList index
i = 0
# List of letters that user will input
letterList = []
# List of words that are our correct answers
solvedList = []
# User inputs 9 letters that will be stored in our letterList
string = input(str("Ange Nio Bokstäver: "))
userInput = False
# Checks if user input is correct
while userInput == False:
# if the string is equal to 9 letters
# insert letter into our letterList.
# also set userInput to True
if len(string) == 9:
userInput = True
for char in string:
letterList.insert(i, char)
i += 1
# If string not equal to 9 ask user for a new input
elif len(string) != 9:
print("Du har inte angivit nio bokstäver")
string = input(str("Ange Nio Bokstäver: "))
# For each word in wordList
# and for each char within that word
# check if said word contains a letter from our letterList
# if it does and meets the requirements to be a correct answer
# add said word to our solvedList
for word in wordList:
for char in word:
if char in letterList:
if len(word) >= 4 and len(word) <= 9 and letterList[4] in word:
print("Char:", word)
solvedList.append(word)
私はに実行する問題ではなく、のみが私のletterList
からの手紙が含まれている印刷ワードで、それが含まれている単語を出力していることです少なくとも1つ私のletterList
からの手紙。これは、例えば、複数の文字がletterList
から入っている場合など、いくつかの単語が複数回出力されることを意味します。
私はしばらくの間これらの問題を解決しようとしてきましたが、私はそれを理解できないようです。私はまた、私のリストの文字のすべての可能な組み合わせを作成し、それらを私のwordlist
と比較する順列を使ってみましたが、作成する必要がある組み合わせの数を考えると解決が遅くなると感じました。
# For each word in wordList
# and for each char within that word
# check if said word contains a letter from our letterList
# if it does and meets the requirements to be a correct answer
# add said word to our solvedList
for word in wordList:
for char in word:
if char in letterList:
if len(word) >= 4 and len(word) <= 9 and letterList[4] in word:
print("Char:", word)
solvedList.append(word)
また、私はPythonの初心者ですから、共有する一般的なヒントがあれば、本当に感謝しています。
ありがとうございましたコードはこの方法でもっときれいに見えますが、私はまだ1つの問題にぶつかります。プログラムが結果を出力すると、letterListの文字を含まない単語が出力されます。たとえば、文字列 "anitsksem"を使用すると、letterListにないb、d、uなどの文字を含む単語が得られます。どのように単語**がletterList **からの文字だけを含んでいることを確かめますか? –
ねえ、私はそれを逃した。更新されたバージョンをチェックし、@PeterYakobを探しているかどうかを確認してください。 –
ありがとう、それは魅力のように動作します。 letterList **の中の個々の文字を使用している単語だけを印刷したいのであれば、時間があれば質問をフォローアップしてください。 letterList = ["a"、 "n"、 "i"、 "b"、 "s"、 "l"、 "s"、 "y"、 "m"]プログラムは、 'abyss' –