首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >写入与另一个文件中的字符匹配的行

写入与另一个文件中的字符匹配的行
EN

Stack Overflow用户
提问于 2017-03-05 01:44:58
回答 1查看 36关注 0票数 0

本质上,我想要写的是与代码中引用的in列表相匹配的文档行。

nodeIDs.txt:

..。有417个物体,

代码语言:javascript
复制
10000
10023
1017
1019
1021
1026
1027
1029
...

依附junction.txt:

..。有73行,

代码语言:javascript
复制
4301: AFDN; afadin, adherens junction formation factor 
1496: CTNNA2; catenin alpha 2 
283106: CSNK2A3; casein kinase 2 alpha 3 
2241: FER; FER tyrosine kinase 
60: ACTB; actin beta 
1956: EGFR; epidermal growth factor receptor 
56288: PARD3; par-3 family cell polarity regulator 
10458: BAIAP2; BAI1 associated protein 2 
51176: LEF1; lymphoid enhancer binding factor 1 

我试图让程序逐行并引用in列表,如果该行的开头字符与列表中的任何字符相匹配,则将该行写入新文档。我在研究数据集,但我不确定这些数据在这里是否有效。

到目前为止我的代码:

代码语言:javascript
复制
ids = []
with open('nodeIDs.txt', 'r') as n:
    for line in n:
        ids.append(line)
n.close()

# Import data from the pathway file and turn into a list
g = []
with open('Adherens junction.txt', 'r') as a:
    for line in a:
        g.append(line)
a.close()

aj = open('Adherens.txt', 'a')
for line in a:
    if ids[i] in line:
    aj.write(line)
aj.close()

你能帮我把这事做好吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-05 02:41:12

这是一些代码,我认为这是你想要的。

代码:

代码语言:javascript
复制
# read ids file into a set
with open('file1', 'r') as f:
    # create a set comprehension
    ids = {line.strip() for line in f}

# read the pathway file and turn into a list
with open('file2', 'r') as f:
    # create a list comprehension
    pathways = [line for line in f]

# output matching lines
with open('file3', 'a') as f:

    # loop through each of the pathways
    for pathway in pathways:

        # get the number in front of the ':'
        start_of_line = pathway.split(':', 1)[0]

        # if this is in 'ids' output the line
        if start_of_line.strip() in ids:
            f.write(pathway)

结果:

代码语言:javascript
复制
2241: FER; FER tyrosine kinase 
56288: PARD3; par-3 family cell polarity regulator 

file1:

代码语言:javascript
复制
10000
56288
2241

file2:

代码语言:javascript
复制
4301: AFDN; afadin, adherens junction formation factor 
1496: CTNNA2; catenin alpha 2 
283106: CSNK2A3; casein kinase 2 alpha 3 
2241: FER; FER tyrosine kinase 
60: ACTB; actin beta 
1956: EGFR; epidermal growth factor receptor 
56288: PARD3; par-3 family cell polarity regulator 
10458: BAIAP2; BAI1 associated protein 2 
51176: LEF1; lymphoid enhancer binding factor 1 

什么是集合理解?

这是:

代码语言:javascript
复制
# create a set comprehension
ids = {line.strip() for line in f}

与以下相同:

代码语言:javascript
复制
# create a set
ids = set()
for line in f:
    ids.add(line.strip())
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42603503

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档