简体   繁体   English

将文本文件的内容导入Python中的列表

[英]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. 这是关于projecteuler问题的42。我想将此文本文件( https://projecteuler.net/project/resources/p042_words.txt )的内容导入python列表中。

I want the list to be like list = ["A","ABILITY",........] Any help is greatly appreciated. 我希望列表像list = [“ A”,“ ABILITY”,........]任何帮助,我们将不胜感激。

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. 文件中的值以逗号分隔,因此您可以使用csv阅读器。 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. [0]是因为CSV文件中只有一行。

lst will now contain: lst现在将包含:

['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. 从技术上讲,对于此文件,单引号引起的剥离就足够了,但为防万一,我添加了公共空格和单引号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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