2017-02-05 10 views
-2

単語ゲーム用の関数を作成しています。単語リストを作成する必要があります。単語リストはwordlist.txtというファイルから作成します。私の最初の考えは、最初にそのファイルを開き、作成しようとしている関数への引数としてオープンファイルを渡すことでした。しかし、最後に私は、オープンファイルのwords_fileから削除された改行を含むすべての単語のリストを返すように提案したことを思い出しました(これはPythonでも可能です)。他の各行についてファイルの各行には、標準英語アルファベットの大文字の単語が含まれていますが、これはupper()と.split()を使用して取得したと思います。 私はこれを大変に張り切っています。どんな助けも役に立つでしょう。事前にありがとうございます。 PS:この種の読み込みファイルに関する情報を探しています。 words_file = askopenfile(mode = 'r'、title = '単語リストファイルを選択する')この場合、とにかく便利ですか?私はあなたがあなたのファイルのソースとしてパラメータを使用したいと仮定していファイルからの単語で構成される単語リストの作成方法

def read_words(words_file): 

    """ (file open for reading) -> list of str 

    Return a list of all words (with newlines removed) from open file 
    words_file. 

    Precondition: Each line of the file contains a word in uppercase characters 
    from the standard English alphabet. 
    """ 
    file = open("C:\Python34\wordlist.txt", "r") 
    return words_file.read(wordlilst.txt).replace("\n", "").upper().split() 
+0

[ファイルがPythonを使用しているかどうかを確認するにはどうすればよいですか?](http://stackoverflow.com/questions/82831/how-do-i-check-whether-a-file-exists-using- python) – Veritasium

+0

申し訳ありませんが、私はその質問とは関係がないと思います。 – user7491985

+0

'askopenfile'は' tkinter'からのものです。 GUIを使ってプログラムを作成すると便利です。ウィンドウ内のファイル名を選択することができます。 – furas

答えて

0

は、これは私の機能構成です。あなたのコードはそれを無視し、ハードコーディングされたファイルをfileに割り当て、存在しないパラメータのreadを呼び出しようとします。 私はこれがあなたが望んかもしれないと思う:

def read_words(words_file): 
words_list = [] # initialize empty word list 
with open(words_file) as file: # open the file specified in parameter 
           # 'with' makes sure to close it again 
    for line in file:   # iterate over lines 
     words_list.append(line.replace("\n", "")) # add every line to list 
           #^remove trailing newline, which iterating includes 
return words_list # return completed list 

リストを返します。これは、read_words("C:\Python34\wordlist.txt")を使用し、あなたのファイルのためにそれを実行します。

関連する問題