は注釈で、あなたが探している何をすべき機能です:
def dictionary(filename):
# Pass the function a filename (string)
# set up a dict to hold the results
result = dict()
# open the file and pass it to enumerate
# this combination returns something like a list of
# (index i.e. line number, line) pairs, which you can
# iterate over with the for-loop
for idx, line in enumerate(open(filename)):
# now take each line, strip any whitespace (most notably,
# the trailing newline character), then split the
# remaining line into a list of words contained in that line
words = line.strip().split()
# now iterate over the list of words
for w in words:
# if this is the first time you encounter this word,
# create a list to hold the line numbers within
# which this word is found
if w not in result:
result[w] = []
# now add the current line number to the list of results for this word
result[w].append(idx)
# after all lines have been processed, return the result
return result
関連機能へのリンク(彼らはwouldn正しく注釈内の「T表示):
open
enumerate
strip
正確に何が欲しいですか?すべての単語とその行番号の辞書? – Arman
これは辞書がどのように機能するか、キーごとに1つの値です。あなたはどんな出力を期待していましたか? – jonrsharpe
あなたが望むならば、各値が数字のリストであるところを作ることができます。あなたは何を望んでいるのですか? – khelwood