python - Replace floats with ints in text files
问题描述
I want to find and replace floats with integers in several text files.
There is one float value per text file which I want to convert. It is always after a specific keyword and has to be multiplied by 10.000.
e.g. the float 1.5 should be turned into the integer 15.000
The other floats after 1.5 don't have to be changed though
def edit(file):
with open(file, 'r') as f:
filedata = f.read()
for line in filedata:
if "keyword" in line:
filedata = filedata.replace(re.search(r"\d+\.\d+", line).group(), str(10000*re.search(r"\d+\.\d+", line).group()))
with open(file, 'w') as f:
f.write(filedata)
I was trying to replace the the float using a regex. But this doesn't work
EXAMPLE FILE EXTRACT
abcdef 178 211 208 220
ghijkl 0 0 0 0
keyword 1.50 1.63 1.56 1.45
解决方案
当您发现自己在循环中使用正则表达式时,您应该在循环之外编译它。
接下来,如果要替换一行中的值,则不应在整个文件中搜索它。
最后,您必须将字符串转换为数字类型才能对其进行操作。如果你不这样做,你只会重复字符串('10' * 2
is '1010'
not 20
nor '20'
)
这是您的代码的可能改进:
def edit(file):
with open(file, 'r') as f:
rx = re.compile(r"\d+\.\d+") # compile the regex only once
filedata = f.readlines() # get a list of the lines of the file
for i, line in enumerate(filedata): # and enumerate them
if "keyword" in line:
val = re.search(r"\d+\.\d+", line).group() # split the complex line
newval = str(int(float(val) * 10000))
filedata[i] = line.replace(val, newval) # replace only the current line
break # no need to proceed further
with open(file, 'w') as f:
f.write(filedata)
推荐阅读
- arrays - 错误:对象作为 React 子对象无效(找到:带有键 {articles} 的对象)
- c# - 将内容上传到 GCP 存储桶的 KMS 权限出现 403 错误
- c++ - 将变量模板限制为类型列表
- angular - 有没有办法在firebase中生成文档的id作为字段?使用 Firestore
- r - 使用 dplyr 将行名作为 id
- java - Java 8 Search ArrayList with Streams 算法失败
- sql - 在从嵌套查询中选择时使用 group by
- pandas - 熊猫合并是如何工作的?
- json - VB.Net JSON 数据导入
- python - 如何将转换字典转换为马尔可夫链中的转换矩阵?