0

簡単な単語ゲームを作成しようとしていますが、プレイヤーが書き込んだ単語が辞書にあるかどうかを確認する必要があります。

今のところ、行ごとに確認できますが、あまり効果的ではないので、より良い方法があることを願っています

import csv

word = raw_input('write your word')

def dict_test(word):
    with open('/home/patryk/Pulpit/slownik.csv', 'r') as dictionary:
        reader = csv.reader(dictionary, delimiter = ' ')

        for row in reader:

             if word not in row:
                print word + ' it doesnt exist in dictionary'
             elif word in row:
                print word + ' ### OK ### '
dict_test(word)
4

2 に答える 2

0

csv ファイルが静的ファイル (メイン スクリプト以外のプロセスで更新されていない) の場合、基本的にはset of words(セットを使用できます - dict を使用して例を挙げます (覚えていませんが、私はセットを使用するよりも速いと思います))

次のことができます

import csv

word_dict = {}

def dict_test(word):
   if word_dict.get(word):
      print word + "### OK ###"
   else:
      print word + "is not in dictionary"

def load_words():
    with open('/home/patryk/Pulpit/slownik.csv', 'r') as dictionary:
        reader = csv.reader(dictionary, delimiter = ' ')

        for row in reader:
             words = row.split()
             for word in words:
                 word_dict[word] = 1

# Load all the contect of csv file ONCE
load_words() 
# Now continue asking user
word = raw_input('write your word')
dict_test(word)
于 2013-08-30T04:11:09.290 に答える
0

リスト検索の各要素に 1 つの単語を含むリストに csv ファイルを読み込むことができる場合は、"word" in dictionary_list. リストはアルファベット順に並べられているため、バイナリ検索を使用するとより高速に検索できます。bisect モジュールはバイナリ検索を使用し、インデックス関数のレシピが含まれています。

from bisect import bisect_left
def index(a, x):
'Locate the leftmost value exactly equal to x'
i = bisect_left(a, x)
if i != len(a) and a[i] == x:
    return i
raise ValueError

その後、これを使用できます

try:
    i = index(dictionary_list,word):
    print word + "== Ok =="
except ValueError:
    print word, "doesn't exist in dictionary"

しかし、これはやり過ぎだと思います。ディクショナリをメモリに読み込むことは十分に高速です。

于 2013-08-30T00:30:31.343 に答える