我需要對文本文件中的每一行執行此操作,然後將其寫入另一個文件。我需要刪除第一個空格並用逗號替換它(,
)。用逗號替換每行中的第一個空格
但是,我不希望這發生在線上的任何其他空白。下面是從輸入文本文件中的一個片段:
Achilles Patroclus
Achilles Triumph of Achilles in Corfu Achilleion
Achilles Antilochus
Achilles Hephaestus
Achilles Shield of Achilles
我需要對文本文件中的每一行執行此操作,然後將其寫入另一個文件。我需要刪除第一個空格並用逗號替換它(,
)。用逗號替換每行中的第一個空格
但是,我不希望這發生在線上的任何其他空白。下面是從輸入文本文件中的一個片段:
Achilles Patroclus
Achilles Triumph of Achilles in Corfu Achilleion
Achilles Antilochus
Achilles Hephaestus
Achilles Shield of Achilles
你可以做這樣的事情:
[",".join(line.split(" ", 1)) for line in lines]
這指出我在正確的方向!這裏是我的解決方案.. 與開放(f_in,'r')作爲fin: 與開放(f_out,'w')作爲fout: 爲fin: fout.write(「,」。join line.split(「」,1))) – lsch91
嘛我不是一個Python程序員,但我會嘗試有助於從正則表達式的單點解決方案看法。
你正在做的是確定第一個字和空白之後它。遵循正則表達式來完成這項工作。
正則表達式:使用(^\b\w*\b)(\s)
標誌:
g
全局搜索。
m
用於多行搜索。
說明:
(^\b\w*\b)
將捕獲行的第一個字。
(\s)
將在第一個單詞之後捕獲空白。您也可以選擇使用?:
以內的非捕獲組,因此它變成(?:\s)
或者根本不捕獲它。
更換做到:
\1,
更換匹配的內容。這將會把捕獲的第一組,因爲它是和,
代替whitespace
使用字符串方法replace(old, new, [count])
的。如果給出可選的參數計數,則僅替換第一個計數事件。
with open("file-path") as fin, open("new_file_path", "w") as fout:
for line in fin:
fout.write(line.replace(' ', ',', 1)
使用re.sub
與^([^\s]*)\s+
:
>>> s
'Achilles Triumph of Achilles in Corfu Achilleion'
>>> re.sub(r'^([^\s]*)\s+', r'\1, ', s)
'Achilles, Triumph of Achilles in Corfu Achilleion'
那麼存在re.sub
第四個參數,它可以像
re.sub(" ", ",", x, cnt=1)
x
使用的是字符串,cnt
表示多少更換你想要
太好了。你已經嘗試了什麼? – idjaw
你的意思是說,在第一個單詞「Achilles」之後放置','? – 2016-03-06 06:09:31