gpt4 book ai didi

python - 为什么 .readlines() 会列出单个字符?

转载 作者:太空宇宙 更新时间:2023-11-04 10:47:06 25 4
gpt4 key购买 nike

我有一个这种格式的文本文件:

EFF   3500.  GRAVITY 0.00000  SDSC GRID  [+0.0]   VTURB 2.0 KM/S    L/H 1.25                            
wl(nm) Inu(ergs/cm**2/s/hz/ster) for 17 mu in 1221 frequency intervals
1.000 .900 .800 .700 .600 .500 .400 .300 .250 .200 .150 .125 .100 .075 .050 .025 .010
9.09 0.000E+00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
9.35 0.000E+00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
9.61 0.000E+00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
9.77 0.000E+00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
9.96 0.000E+00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
10.20 0.000E+00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
10.38 0.000E+00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

...more numbers

我正在努力使 File[0][0] 将打印单词“EFF”等。

import sys
import numpy as np
from math import *
import matplotlib.pyplot as plt

print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)

z = np.array(sys.argv) #store all of the file names into array

i = len(sys.argv) #the length of the filenames array

File = open(str(z[1])).readlines() #load spectrum file

for n in range(0, len(File)):
File[n].split()

for n in range(0, len(File[1])):
print File[1][n]

但是,它一直输出单个字符,就好像每个列表索引都是单个字符一样。这也包括空格。我在一个循环中使用了 split(),因为如果我放入 readlines().split(),它会出错。

输出:

    E
F
F



3
5
0
0
.


G
R
A
V
I

...ect

我做错了什么?

最佳答案

>>> text = """some
... multiline
... text
... """
>>> lines = text.splitlines()
>>> for i in range(len(lines)):
... lines[i].split() # split *returns* the list of tokens
... # it does *not* modify the string inplace
...
['some']
['multiline']
['text']
>>> lines #strings unchanged
['some', 'multiline', 'text']
>>> for i in range(len(lines)):
... lines[i] = lines[i].split() # you have to modify the list
...
>>> lines
[['some'], ['multiline'], ['text']]

如果你想要一个单行的:

>>> words = [line.split() for line in text.splitlines()]
>>> words
[['some'], ['multiline'], ['text']]

使用文件对象应该是:

with open(z[1]) as f:  
File = [line.split() for line in f]

顺便说一句,你在循环时使用了反习语。如果您想遍历一个可迭代对象,只需执行以下操作:

for element in iterable:
#...

如果您还需要元素的索引,请使用enumerate:

for index, element in enumerate(iterable):
#...

在你的情况下:

for i, line in enumerate(File):
File[i] = line.split()

for word in File[1]:
print word

关于python - 为什么 .readlines() 会列出单个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16614861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com