将txt文件中的特定列与常数相乘

  • 本文关键字:常数相 txt 文件 python c++17
  • 更新时间 :
  • 英文 :


我有7列的txt文件…我想用一个常数乘以第三列,保持所有其他列相同,然后输出包含所有列的文件。有人能帮忙吗?

1 2 1
2 2 1
3 2 1

用"14"输出应该像

1 2 14
2 2 14
3 2 14

当你有一个包含7列的文本文件时,你的例子只显示3.
所以我根据你的例子给出了我的答案:


与乘法相关的代码的重要部分如下:
matrix[:,(target_col-1)] *= c_val

下面是完整的PYTHON代码:

import numpy as np
# Constant value (used for multiplication)
c_val = 14
# Number of columns in the matrix 
n_col = 3
# Column to be multiplied (ie. Third column)
target_col = 3
# Import the text file containing the matrix
filename = 'data.txt'
matrix = np.loadtxt(filename, usecols=range(n_col))

# Multiply the target column (ie. 3rd column) by c_val (ie.14)
matrix[:,(target_col-1)] *= c_val
# Save the matrix to a new text file
with open('new_text_file.txt','wb') as f:
np.savetxt(f, matrix, delimiter=' ', fmt='%d')

输出:

new_text_file.txt

1 2 14
2 2 14
3 2 14

这是c++ 17的一个可能的解决方案。

如果您确定输入文件的格式,您可以将代码简化为以下代码:

  • 只需遍历输入流,每3个数字乘以一个常数,并为每10个数字添加新行(您提到每行7个数字,但您的示例包含9个数字)。
  • 注意你需要使用文件流而不是字符串流。
#include <fmt/core.h>
#include <sstream>  // istringstream, ostringstream
void parse_iss(std::istringstream& iss, std::ostringstream& oss, int k) {
for (int number_counter{ 0 }, number; iss >> number; ++number_counter) {
oss << ((number_counter % 3 == 2) ? number*k : number);
oss << ((number_counter % 9 == 8) ? "n" : " ");
}
}
int main() {
std::istringstream iss{
"1 2 1 2 2 1 3 2 1n"
"2 4 2 4 4 5 5 5 6n"
};
std::ostringstream oss{};
parse_iss(iss, oss, 14);
fmt::print("{}", oss.str());
}
// Outputs:
//
//   1 2 14 2 2 14 3 2 14
//   2 4 28 4 4 70 5 5 84

(演示)

可以这样做:

MULTIPLIER = 14
input_file_name = "numbers_in.txt"
output_file_name = "numbers_out.txt"
with open(input_file_name, 'r') as f:
lines = f.readlines()
with open(output_file_name, 'w+') as f:
for line in lines:
new_line = ""
for i, x in enumerate(line.strip().split(" ")):
if (i+1)%3 == 0:
new_line += str(int(x)*MULTIPLIER) + " "
else:
new_line += x + " "
f.writelines(new_line + "n")
# numbers_in.txt:
# 1 2 1 2 2 1 3 2 1
# 1 3 1 3 3 1 4 3 1
# 1 4 1 4 4 1 5 4 1
# numbers_out.txt:
# 1 2 14 2 2 14 3 2 14 
# 1 3 14 3 3 14 4 3 14 
# 1 4 14 4 4 14 5 4 14 

最新更新