Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.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 - Fatal编程技术网

如何在python中使用正则表达式从文本文件中获取数据?

如何在python中使用正则表达式从文本文件中获取数据?,python,regex,Python,Regex,我有一个txt文件,其中有很多信息,但我只想要这样开头的文件: 1. #BEGIN_DRUGCARD DB00001 2. # Generic_Name: Lepirudin import re regex = r'#BEGIN_DRUGCARD\s*(.*)\s*# Generic_Name:\s*(.*)' with open ('drugbank.txt', 'r') as infile: drugs = infile.read() results = re.

我有一个txt文件,其中有很多信息,但我只想要这样开头的文件:

1. #BEGIN_DRUGCARD DB00001

2. # Generic_Name:
Lepirudin
import re    
regex = r'#BEGIN_DRUGCARD\s*(.*)\s*# Generic_Name:\s*(.*)'

with open ('drugbank.txt', 'r') as infile:
    drugs = infile.read()
    results = re.findall(regex,drugs)

with open('Drug_output.txt', 'w') as outfile:
    for match in results:
        outfile.write(match[0] + "\n" + match[1] + "\n\n")
我想在第一种情况下得到以DB00001开头的内容。 在第二种情况下,输入第二行中的内容,然后将它们保存到文本文件中

我有以下脚本,但它不工作,我得到以下错误:

回溯(最近一次呼叫最后一次): 文件“/home/viki/workspace/prbb/drugnames”,第22行,在 药物识别号=行() TypeError:“str”对象不可调用 有什么想法吗

import re    

regex1 = '#BEGIN_DRUGCARD '
regex2 = '# Generic_Name:'

x=y=0

e = open ('drugbank.txt', 'r')
f = open ('Drug_output.txt', 'w')

for line in e.readlines():

    if re.match(regex1, line):
        y=1
        continue

    elif re.match(regex2, line):
        x=1
        continue

if y==1:
    drug_id = line()

if x==1:
    generic_name = line.split()

f.write('drug_id')
f.write('\n\n')
f.write('generic_name')
line()
的意思是“调用名为
line
的函数”,当然这不能工作,因为
line
是一个字符串

但是,您的代码还有其他几个问题。它只会在
drugbank.txt
文件中找到最后的匹配项,因为它会在向文件写入任何内容之前覆盖以前的所有案例,并且在写入内容时,它会写入文本
druge\u id
,而不是变量
druge\u id
)。此外,您使用的
split()
错误。你读过Python教程吗

假设您的
drugbank.txt
包含多个药物,并且每个药物的ID和通用名称始终紧随其后,您可以这样做:

1. #BEGIN_DRUGCARD DB00001

2. # Generic_Name:
Lepirudin
import re    
regex = r'#BEGIN_DRUGCARD\s*(.*)\s*# Generic_Name:\s*(.*)'

with open ('drugbank.txt', 'r') as infile:
    drugs = infile.read()
    results = re.findall(regex,drugs)

with open('Drug_output.txt', 'w') as outfile:
    for match in results:
        outfile.write(match[0] + "\n" + match[1] + "\n\n")

我修正了你的一些识别,但是你应该仔细检查你的语法和/或结构。“不太好用”?请告诉我们您正面临的确切问题。我收到以下错误:回溯(最近一次调用上次):文件“/home/viki/workspace/prbb/drugnames”,第22行,在drug_id=line()TypeError中:“str”对象不可调用非常感谢您的快速响应。我是一个非常初级的人,我在这个脚本上挣扎了一段时间。我尝试了你的脚本,没有收到任何错误消息,但输出文件是空的。