Python Forum

Full Version: Extracting Text
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
So I have a text file. containing around 400 lines of my Instagram following info like Email:username:posts
I want to extract all the usernames into another text file
Can anyone help me?
how do you think you might go about this?
do you have sample data that you can share?
Like:

>>> s = 'Email:username:posts'                                                             
>>> s.split(':')[1]                                                                        
'username'
(Nov-13-2019, 05:44 AM)Larz60+ Wrote: [ -> ]how do you think you might go about this?
do you have sample data that you can share?

I have some Idea, but my code is too messy
That's why I'm not asking for correction in code
(Nov-13-2019, 07:00 AM)Evil_Patrick Wrote: [ -> ]I have some Idea, but my code is too messy
That's why I'm not asking for correction in code


how messy could be 3 lines of code? And it could be 2 lines if you are minimalist
(Nov-13-2019, 07:49 AM)buran Wrote: [ -> ]
(Nov-13-2019, 07:00 AM)Evil_Patrick Wrote: [ -> ]I have some Idea, but my code is too messy
That's why I'm not asking for correction in code


how messy could be 3 lines of code? And it could be 2 lines if you are minimalist

This was my code

delimiterInFile = [':']

with open(r'C:\Users\Evil Patrick\Desktop\Insta.txt', 'r') as file:
    listLine = file.readlines()
    for itemLine in listLine:
        item =str(itemLine)
        for delimeter in delimiterInFile:
            item = item.replace(str(delimeter),' ')
            print(item)
I don't know WTF I was tryiny to do
Here is your code with some comments from me to help. I don't want to give you the solution, as it will be more beneficial to you

delimiterInFile = [':'] # why list? you know it's a semi-colon, no other delimiters
 
with open(r'C:\Users\Evil Patrick\Desktop\Insta.txt', 'r') as file:
    listLine = file.readlines() # you can iterate directly over file, no need to read full file in memory, but this is also ok
    for itemLine in listLine:
        item =str(itemLine) # unnecessary, and itemLine is str anyway
        for delimeter in delimiterInFile: # not necessary
            item = item.replace(str(delimeter),' ') # you don't want to replace, you want to split itemLine at delimiter and take the first relement from resulting list
            print(item)