【问题标题】:Adding stripped line to string/array in Python在Python中将剥离线添加到字符串/数组
【发布时间】:2015-01-30 16:15:39
【问题描述】:

我是一个相当新的程序员。

我目前正在尝试从 .txt 文件中查找数据并将它们添加到字符串或数组中,然后最终将其添加到 .csv 文件中。

我正在查看的数据目前以这种形式存在,在每个 .txt 文件中以随机间隔多次出现:

' 线通量:3.0008e-19 +/- 2.6357e-21 [W/cm^2]'

因此,在阅读了几种访问方法后,我想出了一个不会产生任何错误但也不会打印任何内容的代码:

cwd = os.getcwd()

def open_txt():
    flux = {}
    for file in cwd:
        if file.endswith('.txt'):
            f = open(file,'r')
            lines = f.readlines()
            for line in lines:
                if line.startswith(' Line Flux:'):
                    line.strip(' Line Flux:                        ' + '[W/cm^2]')
                    flux.append(line)
                    print flux

open_txt()

有什么明显的地方我做错了吗?

感谢阅读。任何有帮助的回复将不胜感激。

【问题讨论】:

  • 不确定这是否是您的问题的唯一原因,但strip 不会修改字符串,它会返回一个包含您所需更改的全新字符串。如果你想使用它,你必须将结果分配给某个东西。
  • 不是问题,但您没有关闭文件。将f.close()放在方法的末尾,或者更好的是,使用with open(file) as f:让它自动关闭。
  • flux应该是一个列表[]而不是一个字典{}
  • 你试过regular expressions,因为你知道数据的形式吗?

标签: python strip readlines startswith


【解决方案1】:

这应该可行:

cwd = os.getcwd()

def open_txt():
    flux = []
    for file in os.listdir(cwd):
        if file.endswith('.txt'):
            with open(file,'r') as f:
                lines = f.readlines()
                for line in lines:
                    if line.startswith(' Line Flux:'):
                        output_line = line[11:-8]
                        flux.append(output_line)
                print flux

open_txt()

我使用了 open 来确保文件正确关闭。

Python 切片表示法用于分割第一个和最后一个字符。

将通量更改为列表而不是字典。

我还将打印语句移出 for 循环,以便它只打印完成的数组。

【讨论】:

  • 我假设(可能是错误的)您试图获取删除了“Line Flux:”和“[W/cm^2]”的字符串。如果不是这种情况,则需要使用不同的剥离方法。
【解决方案2】:

getcwd 返回一个字符串,所以我认为这是你的错误所在。您正在遍历字符串的每个字母。也许你需要listdir

您也可以查看link


如果不是这种情况,您可以尝试插入“打印标记”并查看它是否可以打开文件

cwd = os.getcwd()

def open_txt():

    # This has to be a list, not a dict.
    flux = []
    for file in cwd:       

        if file.endswith('.txt'):
            # Check loop is entered, with this print marker
            print 'it opened file: %s'% file

            f = open(file,'r')
            lines = f.readlines()
            for line in lines:
                if line.startswith(' Line Flux:'):
                    line.strip(' Line Flux:                        ' + '[W/cm^2]')
                    flux.append(line)
                    print flux

open_txt()

另外,strip 正在删除您提供给它的所有字符。包括/ : estrip('ab'+'cz') 等价于strip('acbz')

您可以改为使用regular expressions

import re

my_str = ' Line Flux: 3.0008e-19 +/- 2.6357e-21 [W/cm^2]'

pattern = re.compile(r'Line Flux: (.*?)\[W/cm\^2\]')
result = re.findall(pattern, my_str)

print result

模式中的括号表示要返回匹配的哪一部分。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-02
    • 2016-11-04
    相关资源
    最近更新 更多