我有一个文本文件,我正在阅读三个正则表达式。我希望将每个regex搜索中的每个项目逐行合并,并使用与下面最后一行相同的格式打印出来。我就是不能让循环把所有的东西都组合起来。
来自三个不同来源的示例文本(您可以看到信息有时丢失,而其他时候则以不同的格式呈现:
import re
string = open("cusip.txt")
read_string = string.read()
cusip_reg_exp = re.compile('\s[0-9]{3}[a-zA-Z0-9]{6}\s')
cusip_result = cusip_reg_exp.findall(read_string)
bond_name_reg_exp = re.compile('\s[A-Z]{3,5}\s[0-9]{4}\D{1,3}\S{1,3}\s{1,2}\w{1,3}')
bond_name_result = bond_name_reg_exp.findall(read_string)
bond_price_name_reg_ex = re.compile('[$]{0,1}[0-9]{1,2}[-]{1}[0-9]{2}')
bond_price_result = bond_price_name_reg_ex.findall(read_string)
print(cusip_result[0],bond_name_result[0],bond_price_result[0])
发布于 2011-08-19 13:10:15
如果所有这些列表都具有相同的长度,则可以将每个对应条目(由空格分隔)连接起来,以创建组合字符串的列表,然后将这些字符串(由换行符分隔)连接起来,以创建显示的结果列表。我决定用一些列表理解的魔法来做这件事(循环不行!)
print '\n'.join([' '.join([cusip_item, bond_name_item, bond_price_item]) for (cusip_item, bond_name_item, bond_price_item) in zip(cusip_result, bond_name_result, bond_price_result)])
希望这能满足你的需要。如果没有,我相信这个问题还会有其他几种解释:)
编辑:我知道它有点长,但是你可以缩短变量名。或者(或者,另外),您可以在理解之前定义zip(cusip_result、bond_name_result、bond_price_result)。不过,我还是忍不住要做这些事,我喜欢热腾腾的蟒蛇一条线!
https://stackoverflow.com/questions/7127381
复制