python - 在python中将数据从文件导入到字典

标签 python python-3.x

我想将文件导入字典进行进一步处理。该文件包含 NLP 的嵌入向量。看起来像:

the 0.011384 0.010512 -0.008450 -0.007628 0.000360 -0.010121 0.004674 -0.000076 
of 0.002954 0.004546 0.005513 -0.004026 0.002296 -0.016979 -0.011469 -0.009159 
and 0.004691 -0.012989 -0.003122 0.004786 -0.002907 0.000526 -0.006146 -0.003058
one 0.014722 -0.000810 0.003737 -0.001110 -0.011229 0.001577 -0.007403 -0.005355

我使用的代码是:

embeddingTable = {}

with open("D:\\Embedding\\test.txt") as f:
    for line in f:
       (key, val) = line.split()
       d[key] = val
print(embeddingTable)

错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-22-3612e9012ffe> in <module>()
 24 with open("D:\\Embedding\\test.txt") as f:
 25     for line in f:
---> 26        (key, val) = line.split()
 27        d[key] = val
 28 print(embeddingTable)

ValueError: too many values to unpack (expected 2)

我知道它需要 2 个值而不是 9 个值,但是是否可以插入单词作为键和向量作为值?

最佳答案

您需要使用 * operator

embeddingTable = {}
with open("D:\\Embedding\\test.txt") as f:
    for line in f:
       key, *values = line.split() # fix here
       embeddingTable[key] = [float(value) for value in values]
print(embeddingTable)

关于python - 在python中将数据从文件导入到字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34976122/

相关文章:

python - __lt__ 实际为列表做了什么

python - 如何使用 setuptools 安装可写共享和用户特定数据文件?

python - 卡在 100 个请求 uWSGI

python - 未知符号 matplotlib mathtext

python - 按下绘图按钮后 cx_Freeze 转换的 GUI 应用程序 (tkinter) 崩溃

python - 如何使用Python中的现有列以其他列为条件创建新列

python - 使用 Get 访问字典

python - 如何从包含日期和列表中其他字符串的字符串列表中解析月份?

python - 从 ImageMagick 的 Compare.exe 获取终端输出时出现问题(通过管道或 Python)

python - 处理大文件时如何快速获取一行中的多个列?