0

所以。我希望有人可以为我正在尝试做的事情带来一些清晰的表面。

这就是我想做的事情:如果在我指定的(不同且单独的)术语列表(以下简称“terms_list”)中找到文档的措辞,则使用文档索引更改/扩展(不同且单独的)列表。

目前,我已经放置了比较术语列表和在单个函数中扩展索引列表所需的所有代码。为了确保查看数据库中的每个文档,我为每个 terms_list 调用该函数。我想做的是检查我们数据库中的每个文档,看看它是否与我们的 terms_list 中的任何术语匹配。如果是这样,那么我想将该文档的索引添加到索引列表中,这些索引仅适用于或仅与找到文档时正在检查的 terms_list 相关。我希望这有点道理。

也许一些代码将有助于澄清一点:

首先,我创建了我的 terms_list 列表及其相关的索引列表(起初为空)。

something_word_list       = ['term_a', 'term_b', 'term_c']
something_idx_list        = []

another_thing_word_list   = ['term_a', 'term_b', 'term_c']
another_thing_idx_list    = []

然后我创建了一个函数,用于检查当前正在检查的 terms_list 并在必要/适当时扩展 idx_list - 它总是如此。

def get_docs_n_build_idx_lists(terms_n_indices):
    subcat_word_list, subcat_idx_list = terms_n_indices[0], terms_n_indices[1]
    ##initialize db cursor:
    db_conn = crawler_library.connect_to_db("events")
    cursor  = db_conn.cursor()
    ##make query:
    query = "SELECT event_title,description,extra_info,venue_name,idx FROM events WHERE 1"
    #execute the query and catch any errors that show up and print them so I am not flying blind
    try:
        cursor.execute(query)
    except MySQLdb.Error, e:
        print("MySQL Error [%d]: %s") % (e.args[0], e.args[1])
        crawler_library.close_db_connection(db_conn)
    #loop through all results in the query set, one row at-a-time


    if cursor.rowcount > 0: #don't bother doing anything if we don't get anything from the database
        data = cursor.fetchall()
        for row in data:
            temp_string = word_tokenize(nltk.clean_html(str(row[0]).strip(string.digits
            + string.punctuation).lower() +" "+str(row[1]).strip(string.digits +
            string.punctuation).lower() +" "+str(row[2]).strip(string.digits +
            string.punctuation).lower()+" "+str(row[3]).strip(string.digits +
            string.punctuation).lower()))

            temp_string     = [' '.join(word.strip(string.punctuation).split()) for
                       word in temp_string if word not in stopwords and len(word) >= 3]

            bigrams         = nltk.bigrams(word_tokenize(str(' '.join(temp_string))))
            all_terms_list  = temp_string + [str(bigram).replace(",","").replace("'",
                              "").strip("()") for bigram in bigrams]

            subcat_idx_list.extend((str(row[4]) for word in subcat_word_list if word in
            all_terms_list))     

print subcat_idx_list
print "______________________________", "\n"

然后我调用 get_docs_n_build_idx_lists 函数,将 (terms_list, idx_list) 的元组传递给它:

for terms_n_indices in terms_n_indices_list:
    get_docs_n_build_idx_lists(terms_n_indices)

此代码打印出单独的索引列表,因此它按照我们期望的方式工作。然而,我不知道该怎么做是*如何将这些 idx_lists 关联回它们的特定名称*(例如,如果我将数据库文档的术语与其中的术语进行比较,如何扩展 another_thing_idx_list another_thing_word_list)。我需要/希望该函数每次都扩展一个特定的 idx_list,以便以后可以使用它。注意:全局变量不起作用(当然我不完全知道为什么)。注意另外:我可能会依赖一堆条件,但我想避免使用它作为解决方案,因为 terms_lists 和 idx_lists 的数量几乎肯定会增长。

有人可以解释一下最简单或最pythonic的方法吗?提前感谢您的任何帮助,无论多么小。

4

0 回答 0