python - 将单词的前 3 个字符以外的所有字符加星标并删除单独 .txt 文件中的空格的函数
问题描述
获取 .txt 文件(文件名)的副本,然后复制,但用目标 .txt 文件中的字符“*”替换每个单词的前 3 个字符以外的所有字符。如何替换所有空格,以便每个单词后面也跟着一个单数空格?
def speed_reader(file_name, destination):
with open(file_name) as wordfile:
text_str = wordfile.read()
word_list = text_str.split()
output = ""
for word in word_list:
output += word[:3] + ("*" * (len(word)-3))
with open(destination, "w") as writefile:
writefile.write(''.join(output))
这就是我到目前为止所拥有的。
编辑:我刚刚意识到我没有正确地查看输出 .txt 文件。
解决方案
你非常接近。创建一个新的截断单词列表会更容易,然后在写入输出之前用空格将它们全部连接起来。
def speed_reader(file_name, destination):
with open(file_name) as wordfile:
text_str = wordfile.read()
word_list = text_str.split()
out = [w[:3]+('*' * (len(w)-3)) for w in word_list]
with open(destination, "w") as writefile:
writefile.write(' '.join(out))
推荐阅读
- mysql - 从 table2 中找到的 table1 中删除部分列中的值 状态为非活动状态
- testing - ColdFusion 11 到 2018 升级——服务器锁定,如何更好地测试?
- forms - 2019,Chrome 76,关闭自动完成的方法
- ruby - 为什么 google.co.jp 会以 400 Bad Request 响应?
- ios - 关于在 Swift 中重复加载 collectionView 单元格的问题
- postgis - PostGIS 中的 ST_CONTAINS 和 ST_WITHIN 问题
- autohotkey - 从文件中查找数据,并将它们存储为变量
- json - jq - 选择包含特定键的对象
- clojure - 使用 Clojure 的 Ring 提供静态资源
- python - 如何自动弹出窗口?