繁体   English   中英

如何以str格式返回(不打印)所有匹配的行? 字符串是一个长字符串,用\\ t和\\ n分隔

[英]How to return (not print) all matching lines in str format? string is a long string separated by \t's & \n's

def Parser(string):
    string = string.split('\n')    
    import re
    for line in string:
        line = re.search(r"\S+\t+(\S+\t+)\S+\t+\S+\t+(\S+)\t+\S+", line)
        return line.group(1)+line.group(2)

那就是我一直在寻找并最终得到的代码。 感谢提示 ...

def Parser(string):
string = string.split('\n')
firstline = string.pop(0)   
import re
matches = ''
for line in string:
    line = re.search(r"\S+\t+(\S+\t+)\S+\t+\S+\t+(\S+)\t+\S+", line)
    if line:    
        match = line.group(1) + line.group(2)+'\n'
        matches += match
return matches

假设您的其余代码(包括正则表达式)是正确的

def Parser(string):
    string = string.split('\n')    
    import re
    matches = []
    for line in string:
        line = re.search(r"\S+\t+(\S+\t+)\S+\t+\S+\t+(\S+)\t+\S+", line)
        match = line.group(1) + line.group(2)
        matches.extend(match)
    return matches

考虑使用解析器进行输入。 Python随附csv模块:

import csv

def Parser(string):
    output = []

    for fields in csv.reader(string.split('\n'), 'excel-tab'):
        if len(fields) >= 6:
            output.append( fields[1] + '\t' + fields[4] )

    return output

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM