【问题标题】:Extraction of comma separated words after certain strings which are semicolon separated using python在使用python以分号分隔的某些字符串之后提取逗号分隔的单词
【发布时间】:2018-04-19 19:33:19
【问题描述】:

我有一个长文件

Jet pack(human, metal)
thin wire, sheet; fat tube,rod
thin girl;
fat boy;
We like to read
They like to write
End

我想提取“thin”和“fat”之后用逗号分隔的所有单词。这些词也可以单独使用。在任何情况下,即使细和粗都出现在一行上,它们也会用分号分隔。 我的数组将包含:

wire, sheet, tube,rod,girl,boy

我需要一个包含这些单词的数组,然后我将使用它来扩展函数的参数。既然是混合物,我们怎么能用 strip for ;然后再次使用 strip for ,?

干杯

【问题讨论】:

  • 请向我们展示您的尝试和遇到的问题。
  • 请按照您创建此帐户时的建议阅读并遵循帮助文档中的发布指南。 On topichow to ask 在这里申请。 StackOverflow 不是设计、编码、研究或教程服务。
  • @Prune,我什么都不知道,而且我不是开发人员或程序员。所以我只在需要帮助的时候才问!这有什么问题吗?
  • 用-3,我不在乎。我总是可以创建一个新帐户,你可以把它变成-50。毫不在乎。我只是感谢那些愿意提供帮助或准备提供帮助的人。如果你太完美了,就在你们自己之间赢得著名的挑战,不要打扰!
  • @ThierryLathuille,我什么都没尝试,因为我不知道从哪里开始!

标签: python arrays strip


【解决方案1】:

您可以在此处使用正则表达式来提取您需要的值,然后使用re.split() 以逗号或分号分隔:

这是我正在使用的正则表达式:

(?:thin|fat)(.*?)(?=thin|fat|\n)

它将匹配 Thin/fat 之后的任何内容,并且在它找到另一个 Thin/fat 或换行之前。

x = """
Jet pack(human, metal)
thin wire, sheet; fat tube,rod
thin girl;
fat boy;
We like to read
They like to write
End
"""
import re

y = [j.strip() for i in re.findall(r'(?:thin|fat)(.*?)(?=thin|fat|\n)', x) for j in re.split(r'[;,]', i) if j.strip()]
print(y)

输出:

['wire', 'sheet', 'tube', 'rod', 'girl', 'boy']

您提到您在从文件中读取此内容时遇到困难,这是一个从文件中读取的工作示例:

test.txt

Jet pack(human, metal)
thin wire, sheet; fat tube,rod
thin girl;
fat boy;
We like to read
They like to write
End

代码

import re

with open('test.txt') as f:
  y = [j.strip() for i in re.findall(r'(?:thin|fat)(.*?)(?=thin|fat|\n)', f.read()) for j in re.split(r'[;,]', i) if j.strip()]
  print(y)

输出:

['wire', 'sheet', 'tube', 'rod', 'girl', 'boy']

You can try out my solution to see that it works here

【讨论】:

  • 如果我只是将所有文本放在一个文本文件中,然后将该文本文件作为一种通用方式读取,那么最后一个“男孩”就不见了。我复制了文件“trial.txt”中的文本并使用了相同的代码。我曾经将文本读为“x”,如下所示。使用 open('trial.txt', 'r') 作为我的文件:x=myfile.read()
  • 对这个概括有什么建议吗?
  • @HamadHassan 我更新了我的答案,展示了如何从文件中读取。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多