以更快的方式创建词典

2024-05-15 05:36:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含超过500000行的文件。线条如下所示:

0-0 0-1 1-2 1-3 2-4 3-5
0-1 0-2 1-3 2-4 3-5 4-6 5-7 6-7
0-9 1-8 2-14 3-7 5-6 4-7 5-8 6-10 7-11

对于每个元组,第一个数字表示文本a中n行上的一个单词的索引,第二个数字表示同一行n上但在文本b中的一个单词的索引。同样值得指出的是,文本a中的同一个单词可能连接到文本b中的多个单词;与索引0处的行的情况一样,文本a中位置0处的单词是连接的对文本b中位置0和1处的两个单词。 现在我想从上面的行中提取信息,这样就可以很容易地检索文本a中的哪个单词与文本b中的哪个单词相连接。我的想法是使用字典,如下代码所示:

#suppose that I have opened the file as f
for line in f.readlines():
    #I create a dictionary to save my results
    dict_st=dict()
    #I split the line so to get items like '0-0', '0-1', etc.
    items=line.split()  
    for item in align_spl:
        #I split each item at the hyphen so to get the two digits that are now string.
        als=item.split('-')
        #I fill the dictionary
        if dict_st.has_key(int(als[0]))==False:
            dict_st[int(als[0])]=[int(als[1])]
        else: dict_st[int(als[0])].append(int(als[1]))

在提取了所有与文本间单词对应关系相关的信息之后,我再打印出彼此对齐的单词。 现在这个方法非常慢,尤其是当我要从50多万句话中重复它的时候。我想知道是否有更快的方法提取这些信息。 非常感谢。你知道吗


Tags: theto文本信息forthatline数字
1条回答
网友
1楼 · 发布于 2024-05-15 05:36:17

嗨,我不确定这是你需要的

如果每行需要字典:

for line in f:
    dict_st=dict()
    for item in line.split():
        k, v = map(int, item.split('-'))
        dict_st.setdefault(k, set()).add(v)

如果您需要整个文件的字典:

dict_st={}
for line in f:
    for item in line.split():
        k, v = map(int, item.split('-'))
        dict_st.setdefault(k, set()).add(v)

我使用了set而不是list来防止值重复。如果您需要这些重复,请使用“列表”

dict_st={}
for line in f:
    for item in line.split():
        k, v = map(int, item.split('-'))
        dict_st.setdefault(k, []).append(v)

注意:可以使用readlines()在不读取内存的情况下对文件进行迭代

相关问题 更多 >

    热门问题