data = f.readlines()
时间: 2024-05-24 08:10:50 浏览: 16
I'm sorry, as an AI language model, I don't have enough context to provide a proper response. Can you please provide more information or context so I can better understand what you're looking for?
相关问题
import numpy as np import matplotlib.pyplot as plt with open('01_nve_limit.lammpstrj', 'r') as f: data = f.readlines() #print(float(data[0])) for _ in range(9): #next(f) try: while True: a = next(f) print(a) except StopIteration: pass for line in f: #print(line) print(float(data[0])) data = np.loadtxt(f) print(data.reshape(-1,5)) b = np.logical_and(data[ : , 4 ] >= -35 ,data[ : , 4 ] <= 601) data = data[mask] data = data[np.argsort(data[:,4])] x = np.arange(-35, 600, 1) y = np.zeros_like(x) index = 0 for i in range(len(x)): while index < len(data) and data[index,4] < x[i]: index += 1 while index < len(data) and data[index,4] < x[i]+1: y[i] += data[index,5] index += 1 y[i] /= 879.4显示报错:b = np.logical_and(data[ : , 4 ] >= -35 ,data[ : , 4 ] <= 601) IndexError: too many indices怎么解决
这个错误是因为你使用了 `f` 迭代器两次,第一次迭代器已经迭代到了文件的末尾,所以第二次迭代时就没有数据了,导致你尝试访问不存在的数据而出现 `IndexError: too many indices` 错误。
你可以将 `data = np.loadtxt(f)` 这一行代码放在第一个 `for` 循环结束后,这样 `f` 迭代器就不会被耗尽,也不会出现上述错误。修改后的代码如下所示:
```
import numpy as np
import matplotlib.pyplot as plt
with open('01_nve_limit.lammpstrj', 'r') as f:
data = f.readlines()
#print(float(data[0]))
for _ in range(9):
#next(f)
try:
while True:
a = next(f)
print(a)
except StopIteration:
pass
# 将这行代码放在第一个 for 循环结束后
data = np.loadtxt(f)
print(data.reshape(-1,5))
b = np.logical_and(data[ : , 4 ] >= -35 ,data[ : , 4 ] <= 601)
data = data[mask]
data = data[np.argsort(data[:,4])]
x = np.arange(-35, 600, 1)
y = np.zeros_like(x)
index = 0
for i in range(len(x)):
while index < len(data) and data[index,4] < x[i]:
index += 1
while index < len(data) and data[index,4] < x[i]+1:
y[i] += data[index,5]
index += 1
y[i] /= 879.4
plt.plot(x, y)
plt.show()
```
如果你还有其他问题,请随时提出。
import os import re import xlrd import xlwt print("当前路径:", os.getcwd()) file_path = os.getcwd() n = re.split(r'\\', file_path) path = file_path + '\\' + n[5] + ".xls" workbook = xlwt.Workbook(encoding='utf-8') for filename in os.listdir(file_path): if (os.path.splitext(filename)[-1] == ".txt"): data_sheet = workbook.add_sheet(filename[:-4]) data_sheet.write(0, 0, 'No.') data_sheet.write(0, 1, 'test_file_name') data_sheet.write(0, 2, 'rate_ratio') with open(filename, 'r') as f: data = f.readlines() key = 1 sheet_row = 1 while key >= 0: ret = re.search(".bin", data[key]) if ret != None: #print(key) #print(data[key]) #write to excel data_sheet.write(sheet_row, 0, key) data_sheet.write(sheet_row, 1, data[key]) sheet_row = sheet_row + 1 else: break key = key + 1 count = key - 1 count_idx = 1 sheet_row = 1 while key >= 0: ret = re.match("Tensor rate is ", data[key]) if ret != None: #print(count_idx, data[key]) data_sheet.write(sheet_row, 2, data[key][14:]) sheet_row = sheet_row + 1 count_idx = count_idx + 1 key = key + 1 if count_idx > count: break workbook.save(path) 优化上面的代码
上面的代码可以进行如下的优化:
1. 使用`os.path.join()`代替手动拼接路径,可以保证路径的正确性。
2. 使用`with open()`语句打开文件,可以自动管理文件的打开和关闭。
3. 使用正则表达式的`match()`方法代替`search()`方法,因为`search()`方法会在整个字符串中查找匹配,而`match()`方法只会从字符串开头开始匹配。
4. 将重复的代码段抽取为函数,以提高代码的可读性和复用性。
下面是优化后的代码:
```python
import os
import re
import xlwt
def process_file(filename, data_sheet):
with open(filename, 'r') as f:
data = f.readlines()
sheet_row = 1
for line in data:
if line.endswith('.bin\n'):
data_sheet.write(sheet_row, 0, sheet_row)
data_sheet.write(sheet_row, 1, line)
sheet_row += 1
elif line.startswith("Tensor rate is "):
data_sheet.write(sheet_row, 2, line[14:])
sheet_row += 1
def main():
file_path = os.getcwd()
n = re.split(r'\\', file_path)
path = os.path.join(file_path, n[5] + ".xls")
workbook = xlwt.Workbook(encoding='utf-8')
for filename in os.listdir(file_path):
if os.path.splitext(filename)[-1] == ".txt":
data_sheet = workbook.add_sheet(filename[:-4])
data_sheet.write(0, 0, 'No.')
data_sheet.write(0, 1, 'test_file_name')
data_sheet.write(0, 2, 'rate_ratio')
process_file(filename, data_sheet)
workbook.save(path)
if __name__ == '__main__':
main()
```
通过将重复的代码段抽取为函数`process_file()`,提高了代码的可读性和可维护性。同时,使用`os.path.join()`和`with open()`语句更加规范和安全地处理路径和文件操作。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)