I need to perform this operation for every single line in a text file, and then write it to another file. I need to remove the first space and replace it with a comma ( ,).
,
However, I do not want this to happen with any other spaces on the line. Here is a snippet from the input text file:
Achilles Patroclus Achilles Triumph of Achilles in Corfu Achilleion Achilles Antilochus Achilles Hephaestus Achilles Shield of Achilles
You can do something like this:
[",".join(line.split(" ", 1)) for line in lines]
Well, I'm not a python programmer, but I will try to contribute to the solution in terms of regular expressions.
, , whitespace . .
Regex: (^\b\w*\b)(\s)
(^\b\w*\b)(\s)
:
g .
g
m .
m
(^\b\w*\b) .
(^\b\w*\b)
(\s) . , ?: , (?:\s) .
(\s)
?:
(?:\s)
\1,
whitespace
Regex101 Demo
string replace(old, new, [count]). , .
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+:
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)
xis a string, and cntindicates how much you want to replace
x
cnt