优化短语中字符串的搜索。不知道我需要使用哪些 Python 结构



我有一个包含几个单词的文件,后面跟着一个整数(它的权重):

home 10
house 15
village 20
city 50
big 15
small 5
pretty 10
...

等等

我需要对一些短语进行加权,如果它们匹配,则使用它的单词和前一个文件中包含的单词。

"I live in a house in a big city"这个短语权重0 + 0 + 0 + 0 + 15 + 0 + 0 + 10 + 50 = 75

这是我使用Python的第一种方法,即使我有很好的使用C语言的经验:我遇到的困难是我无法达到所需的性能,因为我无法以正确的方式使用正确的Python结构。我能够正确地权衡短语,但使用几个"for"和一个函数调用,就像我使用c一样。

def weight_word(word, words_file):
    fp = open(words_file)
    weight = 0
    line = fp.readline()
    while line:
    # One method I discovered to parse the line where there's
    # a word, a tab and its weight
    left, tab_char, right = line.partition('t')
    if re.match(re.escape(word), left, re.I):
            # The previous re.match didn't guarantee an exact match so I need
            # even to control their lenghts...
        if len(word) == len(left): 
            weight = right
            break
        line = fp.readline()
    fp.close
    return float(weight)
def main():
    my_dict = {"dont parse me":"500", "phrase":"I live in a house in a small city", "dont parse me again":"560"}
    my_phrase = my_dict["phrase"].split()
    phrase_weight = 0
    for word in iter(my_phrase):
        phrase_weight = phrase_weight + weight_word(word, sys.argv[1])
    print "The weight of phrase is:" + str(phrase_weight)

现在我刚刚发现了一些可能对我的情况有用的东西,但我不知道如何正确使用它:

def word_and_weight(fp):
    global words_weight
    words_weight = {}
    for line in fp:
        word, weight = line.split('t')
        words_weight[word] = int(weight)

如何避免前面的for和对我的函数的调用,以及如何使用最后一种按word索引的"数组"?我现在有点糊涂了

您的映射是一个字典:

>>> d = {'foo': 32, 'bar': 64}
>>> d['bar']
64

要得到一个句子的权重,你可以把每个单词的权重加起来:

weight = 0
for word in sentence.split():
    weight += weights[word]

或使用regex:

for word in re.finditer(r'(w+)', sentence):
    ...

您可以使用sum和生成器使其更简洁:

weight = sum(weights[word] for word in sentence.split())

如果字典中没有单词,可以使用dict.get()的第二个参数来返回0,以防某个单词不在字典中:

weight = sum(weights.get(word, 0) for word in sentence.split())

你的第一个算法是打开并解析你的单词文件中的每个单词,这显然是糟糕的,无论语言。您的word_and_weight函数没有那么糟糕,但是您不需要全局变量。假设您有my_dict设置的方式是有原因的,并且不介意权重文件中缺乏输入保护,我将这样做:

import fileinput
def parse_word_weights():
    word_weights = {}
    for line in fileinput.input():
        word, weight = line.strip().split('t')
        word_weights[word] = int(weight)
    return word_weights
def main():
    word_weights = parse_word_weights()
    my_dict = {"dont parse me":"500", "phrase":"I live in a house in a small city", "dont parse me again":"560"}
    my_phrase = my_dict["phrase"].split()
    phrase_weight = sum((word_weights.get(word, 0) for word in my_phrase))
    print "The weight of phrase is:" + str(phrase_weight)

使用fileinput标准库来标准化文件输入——这离唯一的选项还有很长的路要走,但它非常方便。sum调用在生成器表达式上运行,该表达式将依次对每个单词的单词查找进行惰性求值。

显式的for循环将短语权重相加并没有什么错,但是sum调用更习惯。如果您坚持使用for循环,则不需要对my_phrase调用iter—可以直接遍历split的输出。

最新更新