Home > Enterprise >  How to remove every first word from .txt file? [python]
How to remove every first word from .txt file? [python]

Time:11-05

etc.

Apple iPhone 14 > iPhone 14
Samsung Galaxy S22 > Galaxy S22 
Xiaomi Redmi 9 > Redmi 9
John Doe > Doe

Hi! I'd like open .txt file. How to 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 ur file have only a few simple names that repeat etc. "Apple iPhone 12", "Apple iPhone 13", ...

How to 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
  • Related