首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >分析文本文件中的行,在python中

分析文本文件中的行,在python中
EN

Stack Overflow用户
提问于 2011-08-04 19:21:43
回答 7查看 5.2K关注 0票数 1

系统会生成一个文本文件。它包含超过100行。我喜欢在文件中放一行。

代码语言:javascript
运行
复制
some text **
Actions Pending are: Action-1, Action-2,....Action-3 (this is another new line)
some text**

需要将操作放在pending to array中。

我用过

代码语言:javascript
运行
复制
for index in text:
    rc.logMessage(str(index))

它一次打印每个字符,而不是一行。

请告诉我如何解析此文件以将操作放入数组中。

提前感谢

EN

回答 7

Stack Overflow用户

发布于 2011-08-04 19:30:37

类似于:

代码语言:javascript
运行
复制
d = """some text **
Actions Pending are: Action-1, Action-2, Action-3
some text**
"""
res = []
for line in re.findall('Actions Pending are: (.+)', d):
    res.extend([action.strip() for action in line.split(',')])
['Action-1', 'Action-2', 'Action-3']
票数 4
EN

Stack Overflow用户

发布于 2011-08-04 19:28:52

您可以尝试如下所示:

代码语言:javascript
运行
复制
pendingActions = []
textToSearch = 'Actions Pending are:'
for line in open(filename, 'r'):
    line = line.strip()
    if line and line.startswith(textToSearch):
        pendingActions.extend([x.strip() for x in line[len(textToSearch):].split(',') if x.strip()])
票数 3
EN

Stack Overflow用户

发布于 2011-08-04 19:29:05

您需要迭代文件,而不是从文件中读取字符串。

代码语言:javascript
运行
复制
with open(filename) as text:
    for line in text:
         rc.logMessage(some_function_of_the_line(line))

迭代文件得到行;迭代字符串得到字符/字节。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6940500

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档