python - 在python中使用字典用id替换字符串

标签 python dictionary

我有一个字典文件,每行包含一个单词。

标题排序.txt

 a&a    
 a&b    
 a&c_bus    
 a&e    
 a&f    
 a&m    
 ....

对于每个单词,其行号是单词的 id。

然后我有另一个文件,其中包含一组在每行中用制表符分隔的单词。

a.txt

 a_15   a_15_highway_(sri_lanka)    a_15_motorway   a_15_motorway_(germany) a_15_road_(sri_lanka)

如果字典中存在,我想用 id 替换所有单词,这样输出看起来像,

    3454    2345    123   5436     322 .... 

所以我写了这样的 python 代码来做到这一点:

 f = open("titles-sorted.txt")
 lines = f.readlines()
 titlemap = {}
 nr = 1
 for l in lines:
     l = l.replace("\n", "")
     titlemap[l.lower()] = nr
     nr+=1

 fw = open("a.index", "w")
 f = open("a.txt")
 lines = f.readlines()
 for l in lines:
     tokens = l.split("\t")
     if tokens[0] in titlemap.keys():
            fw.write(str(titlemap[tokens[0]]) + "\t")
            for t in tokens[1:]:
                    if t in titlemap.keys():
                            fw.write(str(titlemap[t]) + "\t")
            fw.write("\n")

 fw.close()
 f.close()

但是这段代码慢得离谱,所以我怀疑我是否做对了一切。

这是一种有效的方法吗?

最佳答案

write 循环包含大量对write 的调用,通常效率很低。您可以通过每行只写一次(或者如果文件足够小,则每个文件一次)来加快速度

tokens = l.split("\t")
fw.write('\t'.join(fw.write(str(titlemap[t])) for t in tokens if t in titlemap)
fw.write("\n")

甚至:

lines = []
for l in f:
    lines.append('\t'.join(fw.write(str(titlemap[t])) for t in l.split('\t') if t in titlemap)
fw.write('\n'.join(lines))

此外,如果您的标记被多次使用,您可以通过在阅读时将它们转换为字符串来节省时间:

titlemap = {l.strip().lower(): str(index) for index, l in enumerate(f, start=1)}

关于python - 在python中使用字典用id替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34951158/

相关文章:

python - django.db.utils.IntegrityError : duplicate key value violates unique constraint "spirit_category_category_pkey" 错误

python - 字典理解索引错误

python - 如何访问用于 python 中的 urllib 模块的字典值?

python - 根据两个列表中元组的出现次数更新defaultdict计数

python - Numpy 截断?

python - 访问位于根元素之前的 XML 注释

python - 用于从 werkzeug/Flask 路由规则捕获类型和/或参数化路径的规则

python - 使用 SciPy 的分位数-分位数图

c# - MongoDB 在 InsertOne 上抛出 "MongoDB.Bson.BsonSerializationException"

c# - 如何在字典中插入第一个元素?