首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用反复出现的文本框解析文件,并在不存在元素时添加元素

使用反复出现的文本框解析文件,并在不存在元素时添加元素
EN

Ask Ubuntu用户
提问于 2020-08-04 14:45:12
回答 1查看 61关注 0票数 -3
  • 水果:这是来自德国、荷兰、法国的苹果:成熟的水果橙:维生素C香蕉:d维生素。
  • 水果:这是来自波兰,奥地利橙:C维他命菠萝:一种维生素,有助于消化:使用2天葡萄:维生素B。
  • 水果:这是来自波兰、奥地利的梨:C维他命苹果:成熟的水果,维生素a,b,c-白苹果:{这是用来增强免疫力的一种维生素。
  • 水果:这是来自挪威斯威登的橙子:维生素C菠萝:维生素A葡萄:B维生素。

Requirement:

这是一个有超过1000行的大文件。只有在不存在元素的情况下,我才需要在水果容器中添加元素apple,而不更改现有元素的文件布局结构或位置。

如果有什么不清楚的话,请告诉我.感谢您的支持,提前!

EN

回答 1

Ask Ubuntu用户

发布于 2020-08-04 17:14:15

由于您有一个大文件,我们将单独处理每个容器,而不是在内存中加载整个文件。我们可以很容易地在Python3中做到这一点。将其保存在process.py中,数据保存在fruits_file.txt

代码语言:javascript
复制
import sys

# This function checks if "apple" not in container then append it.
def add_apple_and_print(header, container):
    if container is not None:
        if not any(fruit.startswith("apple") for fruit in container):
            container.append('apple: ripe fruit, vitamin a, b, c')

        print("\n"+header+"\n")
        print("\n\n".join(container))

# Open the file for reading
with open(sys.argv[1]) as f:
    header = None                         # Initialize header with None
    container = None                      # Initialize the container with None
    for line in f:                        # Read line by line
        line = line.strip()               # Remove trailing spaces
        if len(line) > 0:
            if "fruits :" in line:        # if line contains "fruits :"
                add_apple_and_print(header, container) # Print privious container
                header = line                          # Set header
                container = []                         # Create a new container for current fruit section
            else:
                container.append(line)                 # Add fruits to container

    add_apple_and_print(header, container)            # Print last container

然后

代码语言:javascript
复制
python3 process.py fruits_file.txt > fruits_file_with_apple.txt

编辑:在早期的剧本中,“苹果”和“菠萝”是匹配的。因此没有被添加到这样的容器中。修改了脚本。

从SvenMarnach在stackoverflow.com上的答案中获得提示

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

https://askubuntu.com/questions/1264509

复制
相关文章

相似问题

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