首页 > 解决方案 > 将单词的前 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 文件。

标签: python

解决方案


你非常接近。创建一个新的截断单词列表会更容易,然后在写入输出之前用空格将它们全部连接起来。

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))

推荐阅读