在没有用户输入的情况下替换/删除打开的文本文件中的子字符串(Python 3)

2024-06-12 18:03:23 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用Python方法替换手动打开的.txt文件中的子字符串(或删除部分字符串)。 用户已经打开了文本文件,python脚本应该用空格替换该文件中的子字符串(或者删除它,任何更简单的方法)。你知道吗

字符串文本文件如下所示(它是网站的一部分,可以有多行,但为了简单起见,我只放在第一行):

<tr><td>Subtitle</td><td><div class="Current temperature"><!-- here -- <!-- here2 --><div class="London"></div></div><div class="here3"></div><div class="Current temperature"><!-- here4 <!-- /react-text --><div class="Paris"></div></div></td></tr>

最终结果应为两行:

London
Paris

我已经在这里搜索了很多主题,其中很多都假设用户输入的字符串应该被替换,而另一个输入是新字符串。你知道吗

这个小脚本不是那种类型的,它应该已经包含要替换的子字符串(不需要用户输入),因此以下部分:

1.<tr><td>Subtitle</td><td><div class="Current temperature"><!-- here -- <!-- here2 --><div class="
2"></div></div><div class="here3"></div><div class="Current temperature"><!-- here4 <!-- /react-text --><div class="
三。"></div></div></td></tr>

它应该在运行时自动执行。 我也有引号和html标签的问题,所以我经常得到语法错误。你知道吗

在有关此主题的其他主题中,我找到并尝试了以下代码:

file = open("C:/Users/blue11440/Desktop/example-text-file.txt", "r")
str = file.readlines()

x = str.replace("<tr><td>Subtitle</td><td><div class="Current temperature"> 
<!-- here -- <!-- here2 --><div class="", "")

在其他错误中,我发现:

AttributeError: 'list' object has no attribute 'replace'
AttributeError: '_io.TextIOWrapper' object has no attribute 'replace'

我尝试了replace, delete, remove方法,但收效甚微,有没有更好的方法?你知道吗


Tags: 方法字符串text用户div主题herecurrent
1条回答
网友
1楼 · 发布于 2024-06-12 18:03:23

对于最后一个问题:文件.readlines()返回一个列表,其中每行包含一个元素。你知道吗

.replace()是字符串(!)方法。所以试着在列表上迭代:

for line in file.readlines():
    line.replace(....)

编辑:我想你对“在字符串中:结构更换(“副标题

使用单引号可避免这种情况: 结构更换('副标题 你知道吗

相关问题 更多 >