【问题标题】:how to make the space between column 1 and 2 the same如何使第1列和第2列之间的空间相同
【发布时间】:2016-09-06 13:55:07
【问题描述】:

我目前正在尝试过滤词典/词典,使其仅包含我需要的单词。字典有两列,第一列是单词,第二列是音标(见下图)。

词典在here可用。

有没有什么方法可以让这个空格/分隔符即使在所有情况下...这会让事情变得更容易。

【问题讨论】:

  • 这个空间是一个制表符,所以你可以很容易地做for line in file: values = line.split('\t'),然后用values[0]访问单词,用values[1]访问拼音
  • 哦..我觉得自己很愚蠢。它解决了我的问题。非常感谢

标签: python unix text file-handling


【解决方案1】:

您的意思类似于以下内容? here

在这种情况下,这是代码(不使用任何特定字符):

#!/usr/bin/env python2

import sys

path_to_the_file = sys.argv[1]

word = []
pron = []
maxword = 0
with open(path_to_the_file) as fr:
    for line in fr:
        words = line.split()
        word.append(words[0])
        pron.append(' '.join(words[1:]))
        if len(words[0]) > maxword: maxword = len(words[0])

format_str = '{:'+str(maxword)+'s}  {:s}\n'

msg = ''
for w,p in zip(word,pron):
    msg += format_str.format(w,p)

print msg

【讨论】:

    猜你喜欢
    • 2019-09-12
    • 1970-01-01
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多