简体   繁体   English

如何在 Python 3 代码中重写我的 append 行?

[英]How to rewrite my append line in Python 3 code?

My code我的代码

token = open('out.txt','r')

linestoken=token.readlines()
tokens_column_number = 1
r=[]
for x in linestoken:
    r.append(x.split()[tokens_column_number])
token.close()

print (r)

Output Output

'"tick2/tick_calculated_2_2020-05-27T11-59-06.json.gz",'

Desired output所需 output

"tick2/tick_calculated_2_2020-05-27T11-59-06.json.gz"

How to get rid of '' and , ?如何摆脱'',

It would be nice to see your input data.很高兴看到您的输入数据。 I have created an input file which is similar than yours (I hope).我创建了一个与您的相似的输入文件(我希望如此)。

My test file content:我的测试文件内容:

example1 "tick2/tick_calculated_2_2020-05-27T11-59-06.json.gz", aaaa
example2 "tick2/tick_calculated_2_2020-05-27T11-59-07.json.gz", bbbb

You should replace the " , ',' characters.您应该替换" , ',' 字符。

You can do it with replace ( https://docs.python.org/3/library/stdtypes.html#str.replace ):您可以通过replacehttps://docs.python.org/3/library/stdtypes.html#str.replace )来做到这一点:

r.append(x.split()[tokens_column_number].replace('"', "").replace(",", ""))

You can do it with strip ( https://docs.python.org/2/library/string.html#string.strip ):您可以使用striphttps://docs.python.org/2/library/string.html#string.strip ):

r.append(x.split()[tokens_column_number].strip('",'))

You can do it with re.sub ( https://docs.python.org/3/library/re.html#re.sub ):您可以使用re.subhttps://docs.python.org/3/library/re.html#re.sub ):

import re

...
...
for x in linestoken:
    x = re.sub('[",]', "", x.split()[tokens_column_number])
    r.append(x)
...
...

Output in both cases: Output 在这两种情况下:

>>> python3 test.py
['tick2/tick_calculated_2_2020-05-27T11-59-06.json.gz', 'tick2/tick_calculated_2_2020-05-27T11-59-07.json.gz']

As you can see above the output ( r ) is a list type but if you want to get the result as a string, you should use the join ( https://docs.python.org/3/library/stdtypes.html#str.join ). As you can see above the output ( r ) is a list type but if you want to get the result as a string, you should use the join ( https://docs.python.org/3/library/stdtypes.html# str.join )。

Output with print(",".join(r)) : Output 与print(",".join(r))

>>> python3 test.py
tick2/tick_calculated_2_2020-05-27T11-59-06.json.gz,tick2/tick_calculated_2_2020-05-27T11-59-07.json.gz

Output with print("\n".join(r)) : Output 与print("\n".join(r))

>>> python3 test.py
tick2/tick_calculated_2_2020-05-27T11-59-06.json.gz
tick2/tick_calculated_2_2020-05-27T11-59-07.json.gz

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

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