-2

-

嗨朋友们。

我有很多文件,其中包含文本信息,但我只想搜索特定的行,然后在这些行中搜索特定的位置值并将它们与固定值相乘(或通过输入输入)。

示例文本:

1,0,0,0,1,0,0
15.000,15.000,135.000,15.000
7
3,0,0,0,2,0,0
' holep_str ',50.000,-15.000, 20.000 , 20.000 ,0.000
3
3 ,0,0,100,3,-8,0
58.400,-6.600,'14',4.000,0.000
4
3,0,0,0,3,-8,0
50.000,-15.000,50.000,-15.000
7
3, 0,0,0,4,0,0
' holep_str ',100.000,-15.000, 14.000 , 14.000 ,0.000
3
3,0,0,100,5,-8,0
108.400,-6.600,'14',4.000,0.000

我只想识别和修改带有“holep_str”文本的行:

' holep_str ',50.000,-15.000, 20.000 , 20.000 ,0.000
' holep_str ',100.000,-15.000, 14.000 , 14.000 ,0.000

在以字符串“holep_str”开头的每一行中有两个数字,位于第 3 和第 4 位置:

20.000 20.000
14.000 14.000

这些可以被识别为:
1./ 以“holep_str”开头的行的第 3 个逗号后的
数字 2./ 以“holep_str”开头的行的第 4 个逗号后的数字

正则表达式无能为力,Python 可能肯定,但我赶时间 - 并且不再使用该语言......

有没有人可以解释如何编写这个相对简单的代码,找到所有带有“搜索字符串”(=“holep_str”)的行 - 并将第 3 和第 4 个逗号之后的值乘以 FIXVALUE(或值输入 - 例如“2 “)?

代码应该遍历所有具有定义扩展名的文件(由输入选择 - 例如txt),其中执行代码 - 搜索所需行上的所有值并将它们相乘并写回......

所以它看起来像 - 如果 FIXVALUE = 2:
' holep_str ',50.000,-15.000, 40.000 , 40.000 ,0.000
' holep_str ',100.000,-15.000, 28.000 , 28.000 ,0.000

整个文本看起来像这样:
1,0,0,0,1,0,0
15.000,15.000,135.000,15.000
7
3,0,0,0,2,0,0
' holep_str ',50.000,-15.000, 40.000 , 40.000 ,0.000
3
3,0,0,100,3,-8,0
58.400,-6.600,'14',4.000,0.000
4
3,0,0,0,3,-8,0
50.000,-15.000, 50.000,-15.000
7
3,0,0,0,4,0,0
' holep_str ',100.000,-15.000, 28.000 , 28.000 ,0.000
3
3,0,0,100,5,-8,0
108.400,-6.600, '14',4.000,0.000

谢谢你。

4

2 回答 2

0
with open(file_path) as f:
    lines = f.readlines()

for line in lines:
    if line.startswith(r"'holep_str'"):
        split_line = line.split(',')
        num1 = float(split_line[3])
        num2 = float(split_line[4])
        print num1, num2
        # do stuff with num1 and num2

一旦你.split()有了参数的行,,你就会得到一个列表。然后,您可以通过索引找到您想要的值,34您的情况下。我还将它们转换float为最后。

于 2017-03-13T21:39:34.950 回答
0

也是最终解决方案 - 整个程序(版本:python-3.6.0-amd64):

# import external functions / extensions ...
import os  
import glob

# functions definition section
def fnc_walk_through_files(path, file_extension):
   for (dirpath, dirnames, filenames) in os.walk(path):
      for filename in filenames:
         if filename.endswith(file_extension): 
            yield os.path.join(path, filename)

# some variables for counting
line_count = 0

# Feed data to program by entering them on keyboard
print ("Enter work path (e.g. d:\\test) :")
workPath = input( "> " )
print ("File extension to perform Search-Replace on [spf] :")
fileExt = input( "> " )
print ("Enter multiplier value :")
multiply_value = input( "> " )
print ("Text to search for :")
textToSearch = input( "> " ) 

# create temporary variable with path and mask for deleting all ".old" files
delPath = workPath + "\*.old"
# delete old ".old" files to allow creating backups
for files_to_delete in glob.glob(delPath, recursive=False):
    os.remove(files_to_delete)

# do some needed operations...
print("\r") #enter new line
multiply_value = float(multiply_value) # convert multiplier to float
textToSearch_mod = "\'" + textToSearch # append apostrophe to begin of searched text
textToSearch_mod = str(textToSearch_mod) # convert variable to string for later use
# print information line of what will be searched for
print ("This is what will be searched for, to identify right line: ", textToSearch_mod)
print("\r") #enter new line

# walk through all files with specified extension <-- CALLED FUNCTION !!!
for fname in fnc_walk_through_files(workPath, fileExt):
   print("\r") # enter new line
   # print filename of processed file
   print("          Filename processed:", fname )
   # and proccess every file and print out numbers
   # needed to multiplying located at 3rd and 4th position
   with open(fname, 'r') as f: # opens fname file for reading
       temp_file = open('tempfile','w') # open (create) tempfile for writing
       lines = f.readlines() # read lines from f:
       line_count = 0 # reset counter
       # loop througt all lines
       for line in lines:
           # line counter increment
           line_count = line_count + 1
           # if line starts with defined string - she will be processed
           if line.startswith(textToSearch_mod):
               # line will be divided into parts delimited by ","
               split_line = line.split(',')
               # transfer 3rd part to variable 1 and make it float number
               old_num1 = float(split_line[3])
               # transfer 4th part to variable 2 and make it float number
               old_num2 = float(split_line[4])
               # multiply both variables
               new_num1 = old_num1 * multiply_value
               new_num2 = old_num2 * multiply_value
               # change old values to new multiplied values as strings
               split_line[3] = str(new_num1)
               split_line[4] = str(new_num2)
               # join the line back with the same delimiter "," as used for dividing
               line = ','.join(split_line)
               # print information line on which has been the searched string occured
               print ("Changed from old:", old_num1, old_num2, "to new:", new_num1, new_num2, "at line:", line_count)
               # write changed line with multiplied numbers to temporary file
               temp_file.write(line)
           else:
               # write all other unchanged lines to temporary file
               temp_file.write(line)
   # create new name for backup file with adding ".old" to the end of filename
   new_name = fname + '.old'
   # rename original file to new backup name
   os.rename(fname,new_name)
   # close temporary file to enable future operation (in this case rename)
   temp_file.close()
   # rename temporary file to original filename
   os.rename('tempfile',fname)

同样在2天后,在好人的帮助和对语言的刻苦学习的帮助下:-D(缩进是我的噩梦)并在这个网站上使用了一些代码片段,我创建了一些有用的东西...... :-) 我希望它可以帮助其他有类似问题的人...

一开始这个想法很明确 - 但对语言一无所知......

现在 - 一切都可以完成 - 只有人类可以想象的是边界:-)

我想念 Python 中的 GOTO :'( ...我喜欢意大利面条,而不是意大利面条代码,但有时最好有一些标签<--goto跳转...(但事实并非如此...)

于 2017-03-15T14:55:40.760 回答