使用python读取文本表
我有一个表,看起来像这个NB,这是一个小的小节,这里有40多个字段 我想问一下,有没有一种方法可以在Python中阅读并存储为列表列表使用python读取文本表,python,data-structures,text-files,Python,Data Structures,Text Files,我有一个表,看起来像这个NB,这是一个小的小节,这里有40多个字段 我想问一下,有没有一种方法可以在Python中阅读并存储为列表列表 [[804,01000001,jj,01asdas],[804,0100002,hh,1-NetSassassdasdsds]] 您可以扔掉前三个标题行,去掉最外层的|,然后用|作为分隔符拆分该行,最后去掉空白 使用列表理解,假设表文本存储在数据中: 根据评论: import pandas as pd arr = pd.read_csv('path_to_t
[[804,01000001,jj,01asdas],[804,0100002,hh,1-NetSassassdasdsds]]
您可以扔掉前三个标题行,去掉最外层的|,然后用|作为分隔符拆分该行,最后去掉空白 使用列表理解,假设表文本存储在数据中: 根据评论:
import pandas as pd
arr = pd.read_csv('path_to_txt_file.txt', sep='|').values.tolist()
使用以下文本文件进行测试:
h1|h2|h3
abc|foo|bar
abc2|foo2|bar2
输出
>>> pd.read_csv('random.txt', sep='|').values.tolist()
[['abc', 'foo', 'bar'], ['abc2', 'foo2', 'bar2']]
您可以按顺序分析该行,抛出带有破折号的行,拆分文件,并将其附加到列表中
data = []
with open(file) as f:
for line in f:
if '-' not in line:
data.append(line.split('|')[1:-1])
在下面的示例中对其进行了测试
----------------------
|id|f1 |f2 |f3 |
----------------------
|12|01001|jj|01|
|12|01001|jj|01|
打印以下输出
[['id', 'f1 ', 'f2 ', 'f3 '],
['12', '01001', 'jj', '01'],
['12', '01001', 'jj', '01']]
以下是我遵循的步骤- 1.从文本文件中读取行。 2.用pipe |拆分每一行,然后仅提取具有任何字母数字字符的元素。 3.最后,从列表中删除空列表,以省去第1行和第3行 这是代码-
lines = open("test.txt","r").readlines()
l = []
for line in lines :
temp = line.split("|")
l = l + [[x.strip() for x in temp if re.match('^[\w-]+$', x.strip()) is not None]]
finalList = [x for x in l if x != []]
finalList应该给你想要的答案。这张表是从哪里来的?这将推断出如何最容易地读取数据并将其转换为列表。嗨,jhole,我得到了一个txt文件。有定界符吗?没有,没有删除符您的问题使管道字符看起来像是一个定界符,不是吗?
lines = open("test.txt","r").readlines()
l = []
for line in lines :
temp = line.split("|")
l = l + [[x.strip() for x in temp if re.match('^[\w-]+$', x.strip()) is not None]]
finalList = [x for x in l if x != []]