从一个TXT文件构建一个字典元组,输出另一个TXT文件来测试我的字典的准确性

2024-04-26 18:10:34 发布

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

在Spyder中使用Python3.6

我正在尝试创建一个代码,其中我得到以下内容:

-make a dictionary tuple that will keep track of the count showing how often the word and tag appear together in the list

-output the file with a print statement that will give a txt file with the same style as the input file (word position, word, tag)

我这样做是为了我可以使用它与另一个输入文件没有最后一列(字的位置,字),并将分配标签的基础上,我在我的字典。你知道吗

输入文件如图所示(字段以制表符分隔):

1 i PRP

2 want VBP

3 to TO

4 go VB

到目前为止我掌握的密码是

file=open("/Users/Desktop/training.txt").read().split('\n')

d = {}
for i in file:
    if i[1:] in d.keys():
        d[i[1:]] += 1
    else:
        d[i[1:]] = 1

with open('/Users/Desktop/2output.txt', 'w') as file:
for nested_list in d.keys():
    for word in nested_list:
         file.write(word + '\t')
         file.write('\n')

整个代码的结果如下: 我

p
R

'
d级

M
D级

l

k
电子

V
B类

所以我把代码中的单词位置扔掉了。我的问题是:

如何在代码中保持单词的位置?你知道吗

为什么每行只有一个字符?你知道吗

非常感谢。非常感谢您的帮助。你知道吗


Tags: 文件the代码intxtforthatas
1条回答
网友
1楼 · 发布于 2024-04-26 18:10:34

我不知道你说的是什么意思

Everything basically worked except for the writing statement which is outputting a file I can't find anywhere, no bug but its just not working

您的问题可能是在打开写文件时没有提供完整路径。在程序的前面阅读"/Users/Desktop/training.txt",但是稍后打开'2output.txt',没有包含完整路径。我会尝试打开'/Users/Desktop/2output.txt',看看输出文件是否保存在您的桌面文件夹中。你知道吗

相关问题 更多 >