我正在尝试合并多行并按制表符将其分开:
audited 41915 packages in 5.767s
found 596 vulnerabilities (1 low, 2 moderate, 593 high)
run `npm audit fix` to fix them, or `npm audit` for details
但我收到此错误:
TypeError:序列项0:预期的str实例,找到了列表。
输入:
with open('combined.txt', "r") as f:
print(' '.join(line.strip("\n").split("\t") for line in f))
所需的输出:
azubi
arch=pc
mhz#2666
os=linux
ipv6net=auto
adrian
arch=pc
memory#4096
os=solaris11
osdist=opensolaris
答案 0 :(得分:1)
假设您的数据用换行符分隔,则可以使用此代码段读取和格式化数据。
$soapClient = new SoapClient($this->wsdl,
array('location' => $this->EndPointURL."AdaptivePayments/Preapproval/",
'uri' => "urn:Preapproval",
'soap_version' => SOAP_1_1,
'trace' => 1, //debugging option
'compression' => SOAP_COMPRESSION_ACCEPT,
'stream_context' => $ctx)); //adding the stream context option containing the http headers
$response = objectToArray($soapClient->Preapproval($params));
} catch (SoapFault $e) {
$response = objectToArray($e);
}
return $response;
}
这给出了输出:
var row = '<tr>';
row += '<td><input type="text" class="form-control" name="name" id="name"></td>';
row += '<td>';
row += '<select>';
row += '<option value="volvo"> Volvo</option>';
row += '<option value="saab">Saab</option>';
row += '<option value="mercedes">Mercedes</option>';
row += '<option value="audi">Audi</option>';
row += '</select>';
row += '</td>';
row += '<td><input type="text" class="form-control" name="phone" id="phone"></td>';
row += '<td>' + actions + '</td>';
row += '</tr>';
答案 1 :(得分:0)
检查括号的位置,我想应该是
with open(file, "r") as f:
print(' '.join(line.strip("\n").split("\t")) for line in f)
但是,(' '.join(line.strip("\n").split("\t")) for line in f)
将返回generator
,print()
然后在generator
上打印信息,例如<generator object <genexpr> at 0x0000020B62EE1A20>
。我想那不是你想要的。您可以改用:
with open(file, "r") as f:
for line in f:
print(' '.join(line.strip("\n").split("\t")))
编辑:两行获取所需输出的快速修复:
with open(file, "r") as f:
print(' '.join([line.strip() if line != '\n' else line for line in f]).replace('\n ', '\n'))
但是,如果您必须定期加载多个此类文件,我还是很hacky,我建议编写一个适当的文件解析器。
答案 2 :(得分:0)
因此,尽管我认为其他答案已经解决了错误,但它们并没有为您提供预期的输出。
我假设与示例输入一样,在输出中形成1行的文本始终由单个空白行分隔。
我有两种可能的解决方案:
方法1 :
with open('test.txt', 'r') as in_f:
content=in_f.read()
content2 = content.splitlines()
new_lines = []
while content2:
try:
split_idx = content2.index('')
new_lines.append(content2[0:split_idx])
content2 = content2[split_idx+1:]
except ValueError as e:
new_lines.append(content2)
content2 = False
for line in new_lines:
print(' '.join(line))
azubi arch=pc mhz#2666 os=linux ipv6net=auto
adrian arch=pc memory#4096 os=solaris11 osdist=opensolaris
方法2 :
with open('test.txt', 'r') as in_f:
content=in_f.read()
content2 = content.splitlines()
size = len(content2)
idx_list = [idx + 1 for idx, val in enumerate(content2) if val == '']
res = [content2[i: j] for i, j
in zip([0] + idx_list, idx_list +
([size] if idx_list[-1] != size else []))]
for line in res:
print(' '.join(line).strip())
azubi arch=pc mhz#2666 os=linux ipv6net=auto
adrian arch=pc memory#4096 os=solaris11 osdist=opensolaris