簡體   English   中英

如何在 Python 3 代碼中重寫我的 append 行?

[英]How to rewrite my append line in Python 3 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

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

所需 output

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

如何擺脫'',

很高興看到您的輸入數據。 我創建了一個與您的相似的輸入文件(我希望如此)。

我的測試文件內容:

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

您應該替換" , ',' 字符。

您可以通過replacehttps://docs.python.org/3/library/stdtypes.html#str.replace )來做到這一點:

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

您可以使用striphttps://docs.python.org/2/library/string.html#string.strip ):

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

您可以使用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 在這兩種情況下:

>>> 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 )。

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 與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