python - 替换文本文件(注释文件)中每一行的第一个单词(标签)-Python代码
问题描述
我仍然是 Python 的初学者,需要用 .txt 格式修改我的注释标签。.txt 注释格式如下所示:
10 0.31015625 0.634375 0.0890625 0.2625
9 0.37109375 0.35703125 0.0671875 0.2015625
我需要将第一个数字(类号/标签)替换为:
10-->7
9-->6
6-->5
11-->8
8-->5
我已经编写了以下代码,但仍然远远落后于完整的代码,我有点卡住了。
replacements = {'6':'5', '9':'6', '10':'7', '11':'8', '8':'5'}
with open('data.txt') as infile, open('out.txt', 'w') as outfile:
for line in infile:
word=line.split(" ",1)[0]
for src, target in replacements.items():
word = word.replace(src, target)
outfile.write(line)
解决方案
您不必遍历所有替换。您可以检查第一个单词是否在您的替换字典中。我假设您只想替换第一个单词。
word, tail = line.split(" ", 1)
if word in replacements:
word = replacements[word]
outfile.write(word + " " + tail)
您的代码不会更改line
,即更改word
不会更改行,因为它是不同的值。通常,字符串在 Python 中是不可变的(但不是列表),因此您无法通过引用更改字符串对象。对字符串的操作将返回新的字符串对象。
推荐阅读
- javascript - 找不到模块“内部/fs”无法按照现有解决方案工作
- c# - 组合两个表并将它们的查询写入列表
- java - Locale.getDefault() 究竟检索了什么?
- c++ - 从 SQL Server 的 Azure 帐户获取 IP
- dns - 将域添加到虚拟机
- python - 在我的瀑布图中,“虚拟第三轴”的正确 matplotlib 变换是什么?
- markdown - jekyll 中是否有“kramdownify”过滤器?
- excel - 除非单元格包含值,否则如何跳过?
- find - find 命令中的排除目录未正确通过管道传输到 -exec cp
- powershell - 通用列表中的 if 子句