【问题标题】:Creating a 4 column table in python在python中创建一个4列的表
【发布时间】:2023-03-30 15:12:01
【问题描述】:

我有以下数据:

1.
Little Grebe
Tachybaptus ruficollis
टीबुकली
2.
Great Crested Grebe
Podiceps cristatus
मोठी टीबुकली
3.
Black-necked Grebe
Podiceps nigricollis
काळया मानेची टीबुकली
4.
Spot-billed Pelican
Pelecanus philippensis
ठीपक्याच्या चोचीचा झोळीवाला

我需要创建一个看起来像这样的表:

  1. (tab) Little Grebe (tab) Tachybaptus ruficollis (tab) टीबुकली

现在我的代码如下:

f = open("test.txt", "r")

for i in range(2210):  # 2210 is the number of lines in the file
    print(' ')
    for j in range(4):
        print(f.readline(30)+'\t', end='')

感谢您的帮助!

【问题讨论】:

    标签: python file input datatable output


    【解决方案1】:

    您在行迭代器内迭代了 4 次以上,这意味着您最终会运行 f.readline() 8840 次,这可能是预期的。并且没有任何行被区别对待。如果您使用 readline,还需要去掉换行符。否则它也会被打印。对您的代码进行一些小的更改就足以使其工作:

    f = open("test.txt", "r")
    
    for i in range(2210):  # 2210 is the number of items in file
        for j in range(3):
            # Three lines printed with tab
            print(f.readline().strip(), end='\t')
        # And one finishing the row
        print(f.readline().strip())
    

    如果您知道每个新项目都以数字和点开头,那么您可以使用regular expression 查找后面没有的换行符并替换为制表符。

    import re
    with open('test.txt', "r") as f:
        print(re.sub(r'\n(?!\d+\.)', r'\t', f.read()))
    

    【讨论】:

    • 我的意思是文件中的字符串,包括换行符
    • 所以现在,有些情况下数字后面只有2个名字,所以表格列不匹配。有没有办法处理这种边缘情况?我的想法是 - 一旦你遇到一个数字,你检查下一个数字是否出现在 3 行之后,如果没有,那么在那么多列中放置空格。
    • @CheaterLetsGO 好主意。添加了一个解决方案,该解决方案至少更改下一个数字的行,但不会在缺失的列中添加额外的空白
    • @CheaterLetsGO 如果您发现答案有用,您可以将其标记为有用,我会获得更好的声誉:)
    • 我做到了。它说 - 声望低于 15 的人的投票会被记录,但不要更改公开显示的帖子分数。
    【解决方案2】:

    试试这段代码,希望对你有帮助。

    crimefile = open("/home/developer/task.txt", "r")
    
    i = 0
    
    line_list = crimefile.readlines()
    for line_l in line_list:
        if i == 3:
            print(line_l.strip(), end='\n')
            i = 0
        else:
            print(line_l.strip(), end=' ')
            i = i+1
    

    我得到了这个结果:-

    1.  Little Grebe    Tachybaptus ruficollis  टीबुकली
    2.  Great Crested Grebe Podiceps cristatus  मोठी टीबुकली
    3.  Black-necked Grebe  Podiceps nigricollis    काळया मानेची टीबुकली
    4.  Spot-billed Pelican Pelecanus philippensis  ठीपक्याच्या चोचीचा झोळीवाला
    

    【讨论】:

      猜你喜欢
      • 2021-05-13
      • 2022-06-19
      • 1970-01-01
      • 2011-02-27
      • 1970-01-01
      • 1970-01-01
      • 2019-12-25
      • 1970-01-01
      • 2020-09-05
      相关资源
      最近更新 更多