从文本文件规范化字符串数据

时间:2018-05-14 06:18:36

标签: python-3.x text-files

我在textfile中有以下格式的数据,需要将数据标准化为一个在另一个之下,即。

当前数据采用以下形式,

1,354,1116,4296,49888 2,2029 3,7092,12834,26651,52362

需要以下表格中的数据:

1354

1,1116

1,4296

1,49888

2,2029

3,7092

3,52362

1 个答案:

答案 0 :(得分:1)

这是最简单的方法:

1,354 
1,1116 
1,4296 
1,49888 
2,2029 
3,7092 
3,12834 
3,26651 
3,52362 

<强>输出

file = open('test.txt', 'w+')
file.write('1,354,1116,4296,49888 2,2029 3,7092,12834,26651,52362\n')

# file.txt:
#
# 1,354,1116,4296,49888 2,2029 3,7092,12834,26651,52362
#

with open('test.txt', 'a+') as file:
    for line in file.read().split():
        for n, j in enumerate(line.split(',')):
            if n:
                file.write('{},{}\n'.format(line[0], j))

# file.txt:
#
# 1,354,1116,4296,49888 2,2029 3,7092,12834,26651,52362
# 1,354
# 1,1116
# 1,4296
# 1,49888
# 2,2029
# 3,7092
# 3,12834
# 3,26651
# 3,52362
#

<强>更新

public interface PersonRepository extends MongoRepository<Person, String> {
    Page<Person> findByFirstname(String firstname, Pageable pageable);
}