简体   繁体   中英

Import contents of Text file into a List in Python

This is Regarding the projecteuler problem 42. I want to import the content of this text file ( https://projecteuler.net/project/resources/p042_words.txt ) in to a list in python.

I want the list to be like list = ["A","ABILITY",........] Any help is greatly appreciated.

use following code:

mylist=[]
with open('p042_words.txt','r') as f:
    mylist=f.readlines()
l=[]
for i in mylist:
    l=l+i.split(',')
print(l)

if you want remove '"' character from each word use following code:

import re
mylist=[]
with open('p042_words.txt','r') as f:
    mylist=f.readlines()

l=[]
for i in mylist:
    j=re.sub('["]','',i)
    l=l+j.strip('"').split(',')
print(l)

The values in the file are comma separated so you can use the csv reader. It will take care of everything for you.

import csv

with open('p042_words.txt', 'r') as infile:
    lst = [item for item in csv.reader(infile)][0]

the [0] is because there is only one line in the CSV file.

lst will now contain:

['A', 'ABILITY', 'ABLE', 'ABOUT', ...

You'll have to split the words once you load them, then strip the quotation marks from them to get the desired result, ie

with open("p042_words.txt", "r") as f:
    words = [word.strip("\"' \t\n\r") for word in f.read().split(",")]

print(words)
# ['A', 'ABILITY', 'ABLE', 'ABOUT', 'ABOVE', ...]

Technically, for this file simple stripping of quotation marks should be enough, but I've added the common whitespace and single quotation marks just in case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM