Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用字典值替换文件中的字符串_Python_Regex_Dictionary - Fatal编程技术网

Python 用字典值替换文件中的字符串

Python 用字典值替换文件中的字符串,python,regex,dictionary,Python,Regex,Dictionary,我有一个文件(usearch.txt),其中的条目如下所示: 0 AM158981 0 AM158980 0 AM158982 等等 我想用第二个文件(acs.txt)中对应的细菌名称替换该文件(AM158981等)中的登录号: AM158981布氏杆菌科布氏杆菌 AM158980猪布鲁氏菌科布鲁氏菌 AM158982 ceti布鲁氏菌科布鲁氏菌 等等 我的计划是使用第二个文件(登录号作为键,名称作为值)创建一个字典,然后打开第一个文件,使用字典替换登录号并将其保存到一个新文件(done.txt

我有一个文件(usearch.txt),其中的条目如下所示:

0 AM158981
0 AM158980
0 AM158982
等等

我想用第二个文件(acs.txt)中对应的细菌名称替换该文件(AM158981等)中的登录号:

AM158981布氏杆菌科布氏杆菌 AM158980猪布鲁氏菌科布鲁氏菌
AM158982 ceti布鲁氏菌科布鲁氏菌
等等

我的计划是使用第二个文件(登录号作为键,名称作为值)创建一个字典,然后打开第一个文件,使用字典替换登录号并将其保存到一个新文件(done.txt):

我在运行以下脚本时遇到此错误:Traceback(最近一次调用last):

文件“nameit.py”,第21行,在
x=regex.sub(r'\1',名称(名称),行)
TypeError:“dict”对象不可调用
理想情况下,我的“done.txt”文件如下所示:

0布氏杆菌科布氏杆菌 0猪布鲁氏菌科布鲁氏菌

0布鲁氏菌ceti布鲁氏菌科

您试图将
命名器
用作一种方法:

x = regex.sub(r'\1', namer(name), line)
您希望将括号替换为方括号,以便使用键
name
访问元素:

x = regex.sub(r'\1', namer[name], line)
注意:您还需要重新获取名称,否则将反复使用相同的密钥:

with open(infilename, 'r') as infile, open(outfilename, 'w') as outfile:
    for line in infile:
        # Need to get the ID for the bacteria in question. If we don't, everything
        # will end up with the same name in our output file.
        _, name = line.split(" ", 1)

        # Strip the newline character
        name = name.strip()

        x = regex.sub(r'\1', namer[name], line)
        outfile.write(x) 

dict access是namer[name]我将其更改为namer[name]并得到以下信息:TypeError:“dict”对象不可调用我将其更改为namer[name]并得到以下信息:TypeError:“dict”对象不可调用。@Jen完全错误是什么?它应该给你一行它不喜欢的内容。@Jen另外,如果你在
regex.sub
之前打印
name
会发生什么?你确定你修改了正确的文件吗?你安装了它并使用了副本吗?@Jen现在,你只在循环浏览字典文件时将
name
设置为一个值。当您开始循环输入文件以写入输出文件时,
name
从未更改。因此,如果
name
类似于
foo
,则输出文件中的所有内容都将使用名称词典中的
foo
值。我编辑了我的答案,以显示如何获得名称-看看它是否有意义。
x = regex.sub(r'\1', namer[name], line)
with open(infilename, 'r') as infile, open(outfilename, 'w') as outfile:
    for line in infile:
        # Need to get the ID for the bacteria in question. If we don't, everything
        # will end up with the same name in our output file.
        _, name = line.split(" ", 1)

        # Strip the newline character
        name = name.strip()

        x = regex.sub(r'\1', namer[name], line)
        outfile.write(x)