Sample data:
Apple iPhone 14
Samsung Galaxy S22
Xiaomi Redmi 9
John Doe
Desired output:
iPhone 14
Galaxy S22
Redmi 9
Doe
I'd like open a .txt file. How do I remove every first word from every line when file looks similar like there?
On Notepad, I can use CTRL A > Find and replace > "First_Name " > "" > And I got a list of names It's simple when the file have only a few simple names that repeat etc. "Apple iPhone 12", "Apple iPhone 13", ...
How do I do that in Python? It's possible? Each result must be one under the other \n - imo that's the easiest way to paste results into .csv file. Should I append content my .txt file to list and using slicing? Split .txt file?
f = open("text.txt", "r")
a = f.read().split()
a1 = a[1:]
print(a)
print(a1)
CodePudding user response:
This works for me:
with open("sample.txt", "r", encoding="utf8") as f:
for line in f:
separate_words = line.split(" ")
new_line = " ".join(separate_words[1:])
print(new_line, end="")
Output:
$ python test.py
iPhone 14
Galaxy S22
Redmi 9
Doe
CodePudding user response:
This is concise and uses regular expressions.
Input: text.txt
Apple iPhone 14
Samsung Galaxy S22
Xiaomi Redmi 9
John Doe
Code
import pathlib
import re
data = pathlib.Path('text.txt').read_text()
for line in data.splitlines():
print(re.match('\w (. )', line).group(1))
Output
iPhone 14
Galaxy S22
Redmi 9
Doe