【问题标题】:Python - replace words in .txt file that contain '-' and are less than 4 charactersPython - 替换 .txt 文件中包含“-”且少于 4 个字符的单词
【发布时间】:2018-02-27 15:27:39
【问题描述】:

我有一个 .txt 文件,而不是我用 python 读取的。我想用空格替换所有包含破折号“-”且少于 4 个字符的单词。有谁知道如何做到这一点?

我现在有这个:

with open('text.txt', 'r') as file:
    filedata = file.read()

filedata = filedata.replace('bla', '')

with open('new text.txt', 'w') as file:
    file.write(filedata)

【问题讨论】:

  • str.replace()len()做一些研究
  • 你有没有尝试过?如果是,请分享。注意:with 下应该有一个缩进。
  • 辛苦了
  • 请阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您描述的问题。 StackOverflow 不是编码或教程服务。
  • 检查字符串内容和字长在本网站的文档、教程和其他问题中有很好的介绍。

标签: python regex text replace hyphenation


【解决方案1】:

下面的程序应该可以完成这项工作

a = open("Location of the file",'r')
b= a.read()
a.close()
c = b.split()
str = ""
for i in c:

    if (((i.find('-')) != -1) and len(i)<4 ):
        pass
    else:
        str = str+i+" "
print(str)
a = open("Location of the file",'w')
a.write(str)
a.close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-19
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 2015-11-24
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    相关资源
    最近更新 更多