[英]python, search .txt file and inject character
对于我对python如何提前处理字符串的无知致歉。 我有一个至少为1000行的.txt文件。 看起来像下面
:dodge
1 6 some description string of unknown length
E7 8 another description string
3445 0 oil temp something description voltage over limit etc
:ford
AF 4 description of stuff
0 8 string descritiopn
我想做的基本上是放一个“;” 在每个字符串之前,所以我将要结束的内容如下
:dodge
1 6 ;some description string of unknown length
E7 8 ;another description string
3445 0 ;oil temp something description voltage over limit etc
:ford
AF 4 ;description of stuff
0 8 ;string descritiopn
我的想法是打开文件,搜索“:”字符,下一行,转到“”字符,转到下一个“”字符并写一个“;”。 另一个想法是如果下一个字符!=“:”,则在文本文件中转到“ / n”字符,然后寻找第二个空格import sys import fileinput
with open("testDTC.txt", "r+") as f:
for line in f:
if ' ' in line: #read first space
if ' ' in line: #read second space
line.append(';')
f.write(line)
f.close()
我知道它离我需要的东西还差得很近,但是自从我在python中进行字符串操作以来已经很长时间了。
您只需要在空白处分割两次并加入字符串,就不需要使用正则表达式来生成简单的重复模式:
with open("testDTC.txt") as f:
for line in f:
if line.strip() and not line.startswith(":"):
spl = line.split(None,2)
print("{} ;{}".format(" ".join(spl[:2]),spl[2]))
要将更改写入原始文件,可以使用带fileinput.input
inplace=True
fileinput.input
:
from fileinput import input
for line in input("testDTC.txt",inplace=True):
if line.strip() and not line.startswith(":"):
spl = line.split(None,2)
print("{} ;{}".format(" ".join(spl[:2]),spl[2]),end="")
else:
print(line,end="")
除了索引,我们可以解压缩:
a, b, c = line.split(None,2)
print("{} {} ;{}".format(a, b, c),end="")
输出:
:dodge
1 6 ;some description string of unknown length
E7 8 ;another description string
3445 0 ;oil temp something description voltage over limit etc
:ford
AF 4 ;description of stuff
0 8 ;string descritiopn
对于python 2,您可以删除end=""
并在print语句后使用逗号代替,即print(line),
我们避免使用line.startswith(":")
开头的段落行,而使用if line.strip()
避免空白行。
您可以使用非常简单的算法来执行此操作,而无需调用正则表达式,这样您就可以看到正在发生的事情。
with open('test.txt') as infile:
with open('out.txt', 'w') as outfile:
for line in infile:
if not line or line.startswith(':'): # Blank or : line
outfile.write(line or '\n') # pass it through
else:
line_parts = line.split(None, 2) # split at most twice
try:
# try adding the semicolon after the 2nd space
line_parts[2] = ';' + line_parts[2]
except IndexError:
pass
outfile.write(' '.join(line_parts))
如果您实际上想一次读取一个文件中的字符,则最终会使用read
方法和seek
,但是在Python中这是不必要的,因为您拥有诸如文件迭代和强大的字符串方法之类的高级构造来帮助您。
根据你的榜样,它似乎在你的第二列中,您有一个数字或空格分隔的数字,例如8
, 6
,然后在第三科拉姆这似乎没有任何数字一番介绍。 如果通常是这种情况,则不仅对于此示例,还可以使用此事实来搜索由空格分隔的数字并添加;
之后如下:
汇入
rep = re.compile(r'(\s\d+\s)')
out_lines = []
with open("file.txt", "r+") as f:
for line in f:
re_match = rep.search(line)
if re_match:
# append ; after the found expression.
line = line.replace(re_match.group(1), re_match.group(1)+';')
out_lines.append(line)
with open('file2.txt', 'w') as f:
f.writelines(out_lines)
获得的file2.txt如下:
:dodge
1 6 ;some description string of unknown length
E7 8 ;another description string
3445 0 ;oil temp something description voltage over limit etc
:ford
AF 4 ;description of stuff
0 8 ;string descritiopn
这就是我要做的:
for line in f:
if ' ' in line:
sp = line.split(' ', 2)
line = '%s %s ;%s' % (sp[0], sp[1], sp[2])
由于您只有1000行左右,因此我认为您可以通过使用readlines()一次读取所有内容并为每行使用split来摆脱困境。 如果该行只有一个元素,则打印它,然后调用另一个循环,该循环用多个元素处理后面的行,并用分号和元素的串联代替第三个[2]元素。 然后,您必须根据您的需要执行一些操作以很好地输出行(此处为join,但还有很多其他解决方案)。
with open('testDTC.txt') as fp:
lines = fp.readlines()
for i in xrange(len(lines)):
if len(lines[i].split()) == 1:
print lines[i][:-1]
i += 1
while len(lines[i].split()) > 0:
spl = lines[i].split()
spl[2] = ";"+spl[2]
print " ".join(spl)
i += 1
if i == len(lines):
break
print
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.