【问题标题】:Python Split() function splitting for no apparent reasonPython Split() 函数拆分无明显原因
【发布时间】:2019-09-12 14:00:58
【问题描述】:

我的 split() 函数有问题,由于某种原因,它在不是分隔符“,”的地方进行了拆分。我正在阅读一个逗号分隔的文件,其中包含基因和一些属性。但是当我从文件中读取这一行时

G234064,Essential,GTP/GDP-交换因子 (GEFs),翻译复合物,?,PS00824,1,CELLULAR ORGANIZATION (蛋白质定位于相应的细胞器),细胞质。

但不是拆分为列表中的 9 个不同项目,而是拆分为以下 10 个:

['G240504',
  'Non-Essential',
  '?',
  '?',
  'Sensitivity to aminoacid analogs and other drugs',
  'PS00868',
  '12',
  'CELLULAR ORGANIZATION (proteins are localized to the corresponding '
  'organelle)',
  'cytoplasm.']

我找不到有类似问题的人,这是我使用的代码

def main():
    file = open("Genes_relation.data.txt")
    readfile = file.readlines()
    genlist = []
    for list in readfile:
        genlist.append(list.rstrip("\n").split(","))

我希望输出是

['G240504',
  'Non-Essential',
  '?',
  '?',
  'Sensitivity to aminoacid analogs and other drugs',
  'PS00868',
  '12',
  'CELLULAR ORGANIZATION (proteins are localized to the corresponding 
   organelle)',
  'cytoplasm.']

有人知道发生了什么吗?

【问题讨论】:

  • 问题正文中的行与代码中的行不同。
  • "但不是在列表中拆分为 9 个不同的项目,而是拆分为这 10 个"--那里只有 9 个项目,行尾没有逗号corresponding '跨度>
  • 你能把你的实际输入也放在这里,而不仅仅是预期的输出。它有助于更​​好地理解上下文。
  • 非常仔细地看看你的输出。它有 9 个元素,而不是 10 个。corresponding ' 之后没有 ,。例如。这个['foo' 'bar']['foobar'] 相同。我不知道您究竟是如何获得该输出的,但它有 9 个元素,而不是 10 个。格式只是误导。验证它的最好方法是在拆分后打印长度。
  • 如何显示输出?写入文件或打印到终端都不会将字符串显示为两个字符串,它们将作为文字连接。

标签: python python-3.x split


【解决方案1】:

我试图重现您的错误,但我无法重现。您必须检查文件中的编码,可能有一些意想不到的逗号,或者编码错误。有时在生物数据中存在不同的编码,这会导致不同的意外行为。我不能为你做更多的事情。

>>> x = "G234064,Essential,GTP/GDP-exchange factors (GEFs),Translation complexes,?,PS00824,1,CELLULAR ORGANIZATION (proteins are localized to the corresponding organelle),cytoplasm"
>>> x.split(',')
['G234064', 
'Essential', 
'GTP/GDP-exchange factors (GEFs)', 
'Translation complexes', 
'?', 
'PS00824', 
'1', 
'CELLULAR ORGANIZATION (proteins are localized to the corresponding organelle)',
 'cytoplasm']

【讨论】:

    猜你喜欢
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    相关资源
    最近更新 更多