我已閱讀其他simliar帖子,但它們似乎不適用於我的情況。因此,我在這裏重新發布它。從Python中讀取具有不同行和列大小的文本文件中的值
我有一個文本文件有不同的行和列的大小。我對具有特定參數的值行感興趣。例如。在下面的示例文本文件中,我想要在第二個位置具有數字「1」的每行的最後兩個值。也就是說,我想從值'101到104'開始的行中的值爲'1,101','101,2','2,102'和'102,3',因爲它們具有數字'1'在第二個位置。
$MeshFormat
2.2 0 8
$EndMeshFormat
$Nodes
425
.
.
$EndNodes
$Elements
630
.
97 15 2 0 193 97
98 15 2 0 195 98
99 15 2 0 197 99
100 15 2 0 199 100
101 1 2 0 201 1 101
102 1 2 0 201 101 2
103 1 2 0 202 2 102
104 1 2 0 202 102 3
301 2 2 0 303 178 78 250
302 2 2 0 303 250 79 178
303 2 2 0 303 198 98 249
304 2 2 0 303 249 99 198
.
.
.
$EndElements
的問題是,與我已經提出了下面提及的代碼時,它從「101」開始,但它從其它線路高達「304」或多個讀取值。我做錯了什麼或有人有更好的方法來解決這個問題?
# Here, (additional_lines + anz_knoten_gmsh - 2) are additional lines that need to be skipped
# at the beginning of the .txt file. Initially I find out where the range
# of the lines lies which I need.
# The two_noded_elem_start is the first line having the '1' at the second position
# and four_noded_elem_start is the first line number having '2' in the second position.
# So, basically I'm reading between these two parameters.
input_file = open(os.path.join(gmsh_path, "mesh_outer_region.msh"))
output_file = open(os.path.join(gmsh_path, "mesh_skip_nodes.txt"), "w")
for i, line in enumerate(input_file):
if i == (additional_lines + anz_knoten_gmsh + two_noded_elem_start - 2):
break
for i, line in enumerate(input_file):
if i == additional_lines + anz_knoten_gmsh + four_noded_elem_start - 2:
break
elem_list = line.strip().split()
del elem_list[:5]
writer = csv.writer(output_file)
writer.writerow(elem_list)
input_file.close()
output_file.close()
*編輯:用來尋找像two_noded_elem_start參數的一段代碼如下:
# anz_elemente_ueberg_gmsh is another parameter that is found out
# from a previous piece of code and '$EndElements' is what
# is at the end of the text file "mesh_outer_region.msh".
input_file = open(os.path.join(gmsh_path, "mesh_outer_region.msh"), "r")
for i, line in enumerate(input_file):
if line.strip() == anz_elemente_ueberg_gmsh:
break
for i, line in enumerate(input_file):
if line.strip() == '$EndElements':
break
element_list = line.strip().split()
if element_list[1] == '1':
two_noded_elem_start = element_list[0]
two_noded_elem_start = int(two_noded_elem_start)
break
input_file.close()
你確定這始於101?跳過前面幾行的代碼在哪裏?這段代碼與你所解釋的沒有任何相似之處。 – zvone
是的,第一行'1'以101開頭。我發佈的其他代碼。 –