gpt4 book ai didi

python - 数据操作: Stemming from a inability to select lists

转载 作者:太空宇宙 更新时间:2023-11-03 19:29:40 25 4
gpt4 key购买 nike

我对 python 很陌生,没有真正的编程知识。在我目前的工作中,我被要求从大约 500 多个文件中获取文本形式的数据并将它们绘制出来。我在一定程度上理解绘图,但我似乎无法弄清楚如何以易于选择特定部分的方式操作数据。目前,这是我打开文件的方法:

fp=open("file")
for line in fp:
words = line.strip().split()
print words

结果是它为我提供了文件每一行的列表,但我只能访问最后一行。有人知道一种方法可以让我选择列表的不同变体吗?非常感谢!!

最佳答案

从文件中获取行列表的最简单方法如下:

with open('file', 'r') as f:
lines = f.readlines()

现在您可以拆分这些行或对它们执行任何您想要的操作:

lines = [line.split() for line in lines]

我不确定这是否能回答您的问题 - 如果您有更具体的想法,请告诉我。

<小时/>

由于我完全不明白您所问的内容,因此这里有一些有关如何处理文本文件的示例。您可以在交互式解释器中进行实验,通常只需在命令行中键入“python”即可访问该解释器。

>>> with open('a_text_file.txt', 'r') as f:
... text = f.read()
...
>>> text
'the first line of the text file\nthe second line -- broken by a symbol\nthe third line of the text file\nsome other data\n'

这是文件的原始、未处理的文本。这是一个字符串。字符串是不可变的——它们不能被改变——但它们可以部分或全部复制。

>>> text.splitlines()
['the first line of the text file', 'the second line -- broken by a symbol', 'the third line of the text file', 'some other data']

splitlines 是一个字符串方法。 splitlines 在找到 \n(换行符)字符的地方分割字符串;然后它返回一个列表,其中包含字符串各个部分的副本。

>>> lines = text.splitlines()

这里我刚刚将上面的行列表保存到一个新的变量名称中。

>>> lines[0]
'the first line of the text file'

列表通过索引访问。只需提供从 0len(lines) - 1 的整数即可返回相应的行。

>>> lines[2]
'the third line of the text file'
>>> lines[1]
'the second line -- broken by a symbol'

现在您可以开始操纵单行。

>>> lines[1].split('--')
['the second line ', ' broken by a symbol']

split 是另一种字符串方法。它类似于 splitlines,但您可以指定要用作分界符的字符或字符串。

>>> lines[1][4]
's'

您还可以对字符串中的字符进行索引。

>>> lines[1][4:10]
'second'

您还可以“切片”字符串。结果是字符 4 到 9 的副本。10 是停止值,因此第 10 个字符不包含在切片中。 (您也可以对列表进行切片。)

>>> lines[1].index('broken')
19

如果要查找字符串中的子字符串,一种方法是使用index。它返回子字符串第一次出现的索引。 (如果子字符串不在字符串中,它会抛出错误。如果您不想这样做,请使用 find,如果子字符串不在字符串中,它会返回 -1。)

>>> lines[1][19:]
'broken by a symbol'

然后你可以用它来切片字符串。如果您不提供停止索引,它只会返回字符串的其余部分。

>>> lines[1][:19]
'the second line -- '

如果您不提供开始索引,它将返回字符串的开头并在停止索引处停止。

>>> [line for line in text.splitlines() if 'line' in line]
['the first line of the text file', 'the second line -- broken by a symbol', 'the third line of the text file']

您还可以使用 in ——这是一个 bool 运算,如果子字符串位于字符串中,则返回 True。在本例中,我使用列表理解来仅获取其中包含 'line' 的行。 (请注意,列表中缺少最后一行。它已被过滤。)

如果您还有其他问题,请告诉我。

关于python - 数据操作: Stemming from a inability to select lists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6586651/

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