【问题标题】:why python is printing 2 "the"s, is an error?为什么 python 打印 2 个“the”,是一个错误?
【发布时间】:2021-02-19 05:25:26
【问题描述】:

我的代码必须把文件和所有单词放在一个列表中,然后检查它们是否不重复,如果需要删除它们直到它只有1。但是,只有“the”把它放了几次 在此处输入代码:

    plbrs_totales = list()
    fnombre = input("Ingrese nombre de archivo:\n")
    try:
      llave = open(fnombre)
    except:
      print("Error")
      quit()
    for lineas in llave:
      lineas_ind= lineas.rstrip()
      plbrs = lineas_ind.split()
      plbrs_totales = plbrs_totales + plbrs
    for rep in plbrs_totales:
      repwords = plbrs_totales.count(rep)
      if repwords > 1:
       plbrs_totales.remove(rep)
    plbrs_totales.sort()
    print(plbrs_totales)

y este es el archivo.txt:

But soft what light through yonder window breaks\n
It is the east and Juliet is the sun\n
Arise fair sun and kill the envious moon\n
Who is already sick and pale with grief\n

这是输出,为什么是 2 “the”?

['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', '东方','羡慕','公平','悲伤','是','杀','光','月亮', '苍白','生病','柔软','阳光','the','the','through','what', 'window', 'with', '那边']

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    那是因为您正在修改您正在迭代的列表。 This 应该回答原因。

    至于你如何做到这一点,你会想用这个替换第二个for 循环。

    plbrs_totales = list(set(plbrs_totales))
    plbrs_totales.sort()
    print(plbrs_totales)
    

    set 方法将返回一个 setplbrs_totales 中的每个项目都出现一次,而 list 方法将 set 转换回 列表

    【讨论】:

    • 我现在明白了,但是为什么唯一打印不好的元素是“the”,如果您看到“and”它的效果很好。这是因为我修改了列表吗?
    • 是的。您的文本中只有 3 个 the,所以我猜测 for 循环只能看到一个,因此只删除了一个。
    猜你喜欢
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 2021-05-28
    • 2021-12-08
    相关资源
    最近更新 更多