Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python使用这些条件处理文本文件_Python_String_Io_Strip - Fatal编程技术网

Python使用这些条件处理文本文件

Python使用这些条件处理文本文件,python,string,io,strip,Python,String,Io,Strip,我正在尝试用一些条件清理文本文件 我的文本显示如下 NHIST_0003(ZS.MC.BGE.0424spvco)(21.12)14.08 (ZS.MC.BLK.0424SPVCOS)(21.12)14.08 (ZS.MC.GRY.0424spvco)(21.12)14.08 (ZS.MC.BLK.0525SPCOS3)(21.12)14.08 (ZS.MC.GRY.0525SPCOS2)(21.12)14.08 NHIST_0004(ZS.MC.BGE.0424spvco)(21.12)14.

我正在尝试用一些条件清理文本文件

我的文本显示如下

NHIST_0003(ZS.MC.BGE.0424spvco)(21.12)14.08
(ZS.MC.BLK.0424SPVCOS)(21.12)14.08
(ZS.MC.GRY.0424spvco)(21.12)14.08
(ZS.MC.BLK.0525SPCOS3)(21.12)14.08
(ZS.MC.GRY.0525SPCOS2)(21.12)14.08
NHIST_0004(ZS.MC.BGE.0424spvco)(21.12)14.08

我需要删除第一行前面的任何文本”(“如果该行前面有文本,则删除括号,并删除我要保留的文本的括号。我还需要删除带括号的数字。查看第一行,我只想保留

ZS.MC.BGE.0424SPVC0S14.08

这些都是我试图把事情联系起来的代码。我不想使用重新表达,因为在这个阶段对我来说太超前了

fileName='reach.txt'
fileName2='outreach.txt'


while True:
    f=open(fileName,'r')
    for words in f:
        x=words.split('(', 1)[-1]
        g = open(fileName2,'w')
        g.write(x)
        g.close()
这个循环是无限的。我认为关闭文件是在告诉系统停止处理行

fileName='reach.txt'
fileName2='outreach.txt'

def isfloat(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

g = open(fileName2, 'w')
with open(fileName, 'r') as fh:
    for row in fh:
        x = row.split()
        for item in x:
            if '(' in item and ')' in item:
                first = item.strip('()')
                break
        for i in range(-1, 0-len(x), -1):
            second = x[i]
            if isfloat(second):
                break
        print(first, second)
        g.write(' '.join((first, second)) + '\n')
g.close()
其中:

ZS.MC.BGE.0424SPVCOS 14.08
ZS.MC.BLK.0424SPVCOS 14.08
ZS.MC.GRY.0424SPVCOS 14.08
ZS.MC.BLK.0525SPVCOS3 14.08
ZS.MC.GRY.0525SPVCOS2 14.08
ZS.MC.BGE.0424SPVCOS 14.08
这段代码将处理数据中的各种错误。
例如,如果浮点值不在将要覆盖的最末端,如果
(…)
数据不固定在第二个位置,而是第一个位置,那么也将覆盖它。

如果每行都有类似
(您想要的代码)(您不想要的东西)
的内容,您可以尝试使用正则表达式

正则表达式
“(\([A-z0-9\.]*\)”
匹配以下任意组合(由
[]*
表示):

  • 字母(
    A-z
  • 编号(
    0-9
    ),以及
  • 句号(
    \.
在括号内(
\(\)


从您的示例中,始终会有两个匹配项,例如
ZS.MC.BLK.0424SPVCOS
21.12
re.findall
将按照给定的顺序找到这两个匹配项。因为您想要的总是第一个,所以使用
re.findall(regex,line)[0]

您可以像这样循环文件中的行:

with open('filename.txt') as f:
    for line in f.readlines():
        #do stuff
要从所需行获取信息,可以执行以下操作:

cleaned = []
items = line.split()
for item in items:
    if item.startswith('(') and item.endswith(')'):
        cleaned.append(item.strip('()'))
        break
cleaned.append(items[-1])
cleaned = ' '.join(cleaned)
完整程序:

in_file = 'reach.txt'
out_file = 'outreach.txt'

def clean(string):
    if not string:
        return string

    cleaned = []
    items = string.split()
    for item in items:
        if item.startswith('(') and item.endswith(')'):
            cleaned.append(item.strip('()'))
            break
    cleaned.append(items[-1])
    return ' '.join(cleaned)

with open(in_file) as i, open(out_file, 'w') as o:
    o.write('\n'.join([clean(line) for line in i]))
通过您的示例
reach.txt
,我得到

ZS.MC.BGE.0424SPVCOS 14.08
ZS.MC.BLK.0424SPVCOS 14.08
ZS.MC.GRY.0424SPVCOS 14.08
ZS.MC.BLK.0525SPVCOS3 14.08
ZS.MC.GRY.0525SPVCOS2 14.08
ZS.MC.BGE.0424SPVCOS 14.08

用open(file,'r')作为fh:for行在fh:row[:row.find('(')]
或只做
row.split()
并取下你想要的部分。例如
x=row.split()
x[1],x[3]
但是x=row.split()和x[1],x[3]即使文本文件的格式不完全相同也可以工作?它没有,所以我重新编写了代码以查找
(…)
,然后获取行中的最后一项,因为这似乎是一致的。尝试了我的最新编辑,结果与您的“我想要此结果”匹配:或者只对f中的行执行
,同样的事情。由于缺少
,这也会导致语法错误(为您修复)太棒了!!非常感谢。我喜欢你写的。可读性很强,也很简单。蝎子神喜欢这段代码,但提示了一个索引外的错误,上面写着第16行和第16行11@weemo那么你的文本文件中也有空行了吗?它现在可以处理空行了。现在还不能得到re。对我来说太超前了。读一下吧,我只是没有得到答案wildcards@weemo
只表示任意字符。因此
'a..
将匹配以
'a'
开头的任意三个字符串。感谢所有这些..将每个字符串都读取并通读…非常感谢反馈值错误:需要超过1个值才能读取unpack@weemo:显示输入。我怀疑文件末尾有空行。如果是,编辑应该可以帮助我发布整个文本文件?是4000行。不严格遵循格式unfortunately@weemo:我们需要一个最小的工作示例。因此,要么在OP中发布一组所有可能的行,要么描述所有可能的行,以便提供更可靠的解决方案
blacklist = set('1234567890.')
with open('reach.txt') as infile, open('outreach.txt', 'w') as outfile:
    for line in infile:
        line = line.strip()
        if not line:
            continue
        _left, line = line.split("(", 1)
        parts = [p.rstrip(")").lstrip("(") for p in line.split()]
        parts = [p for i,p in enumerate(parts) if not all(char in blacklist for char in p) or i==len(parts)-1]
        outfile.write("%s\n" %(' '.join(parts)))
ZS.MC.BGE.0424SPVCOS 14.08
ZS.MC.BLK.0424SPVCOS 14.08
ZS.MC.GRY.0424SPVCOS 14.08
ZS.MC.BLK.0525SPVCOS3 14.08
ZS.MC.GRY.0525SPVCOS2 14.08
ZS.MC.BGE.0424SPVCOS 14.08