【问题标题】:Python Replacing Values in a ListPython 替换列表中的值
【发布时间】:2021-06-29 17:50:02
【问题描述】:

我有一个如下所示的列表:

stuff = ['\n', '<td><nobr>8h</nobr></td>', '\n', '<td><nobr>2021-04-02 14:27:44.729</nobr></td>', '\n', '<td class="text-right">1.73</td>;', '\n']

我正在尝试清理它,使其看起来像这样:

stuff = ["8h","2021-04-02 13:27:44.729","1.73"]

我想要做的是:

for x in range(0,len(stuff),1):
     stuff[x] = stuff[x].replace("\n","")
     stuff[x] = stuff[x].replace("<td>","")

如果字符存在,我希望删除它们。如果没有,我希望这部分会被跳过。

我得到的错误信息是

NoneType 对象不可调用。

有什么建议吗?

编辑#1

我相信这与 \n 值搞砸了有关。我不确定这是否准确,但这是我的感觉。

【问题讨论】:

  • 为什么是for x in range(0,len(stuff),1): 而不是for x in stuff:?此外,这可能会有所帮助:Python code to remove HTML tags from a string.
  • 我会看一下链接,但使用 for x in range(0,len(stuff),1) 就是我一直这样做的方式。是否有理由使用 1 而不是另一个?
  • 我在想,如果你在循环之前不小心将东西设置为 None。您是否尝试过使用断点单步执行代码并对其进行调试?另外,我假设在您的实际代码中,数组内容中的第二项也是一个字符串。现在只有 \n 是一个字符串。
  • for x in stuff 更干净 - 除非您特别需要计算索引
  • 如果你已经安装了,你可以使用beautifulsoup(好像你从网上抓取了这些数据)。然后从列表的每个元素中获取文本:soup = BeautifulSoup("8h", "lxml") soup.find("td").text

标签: python python-3.x


【解决方案1】:

如果我的理解是正确的,你要删除两类内容:

  1. &lt;&gt; 之间的任何内容;
  2. 不受欢迎的字符列表,例如\n;

下面的 sn-p 完成了这项工作。


stuff = ['\n', '<td><nobr>8h</nobr></td>', '\n', '<td><nobr>2021-04-02 14:27:44.729</nobr></td>', '\n', '<td class="text-right">1.73</td>;', '\n']

import re
ans = []
for x in stuff:
    x = re.sub(r"<.*?>", "", x) # remove <>
    x = re.sub(r"(\n|;)", "", x) # remove unwanted characters
    if x: ans.append(x)

print(ans) 

【讨论】:

    【解决方案2】:

    我应该说我绝对不为我的代码感到自豪,但这是我想出的:

    import re
    stuff = ['\n', '<td><nobr>8h</nobr></td>', '\n', '<td><nobr>2021-04-02 14:27:44.729</nobr></td>', '\n', '<td class="text-right">1.73</td>;', '\n']
    def get_stuff(el):
        pattern1 = "<td><nobr>(?P<inner>.+)<\/nobr><\/td>"
        pattern2 = "<td class=(\s+)?\".+\"(\s+)?>(?P<inner>.+)\<\/td>"
        result1 = re.search(pattern1, el)
        result2 = re.search(pattern2, el)
        if result1:
            return result1.group("inner")
        if result2:
            return result2.group("inner")
    last_list = list(map(get_stuff, stuff))
    print( [x for x in last_list if x is not None])
    

    结果

    ['8h', '2021-04-02 14:27:44.729', '1.73']
    

    更新

    所以我想出了一个更好的主意(仍然不自豪)

    import re
    stuff = ['\n', '<td><nobr>8h</nobr></td>', '\n', '<td><nobr>2021-04-02 14:27:44.729</nobr></td>', '\n', '<td class="text-right">1.73</td>;', '\n']
    def get_stuff(el):
        pattern = "\<(\/)?nobr\>|\<(\/)?td(\s+)?(class(\s+)?\=(\s+)?\".+\"(\s?))?>|\\n|\;"
        a  = re.sub(pattern, "", el)
        return a
    last_list = list(map(get_stuff, stuff))
    print( [x for x in last_list if x != ''])
    

    结果(还是一样)

    ['8h', '2021-04-02 14:27:44.729', '1.73']
    

    【讨论】:

    • 我会玩它,无论任何人有任何解决方案仍然比我目前拥有的更好。谢谢
    猜你喜欢
    • 1970-01-01
    • 2022-11-10
    • 2010-11-07
    • 2015-07-13
    • 1970-01-01
    • 2023-01-11
    • 2019-07-28
    • 2022-07-03
    • 1970-01-01
    相关资源
    最近更新 更多