将.txt中不同长度的句子转换为Python中带有2列的.csv文件

2024-06-09 17:16:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个.txt文件,其中包含不同长度的句子,其各自的ID附加在开头。 像这样:

MR1 firstWord secondWord thirdword fourthWord
MR2 some sentence written again.
MR3 some other sentence with variable length of words.

我想把它转换成两列的.csv文件:

MR1 firstWord
MR1 secondWord
MR1 thirdWord
MR1 fourthWord
MR2 some
MR2 sentence
.....
....
....

我的逻辑是应用一个双for循环来实现这一点,但是用我的逻辑输出文件是这样的:

MR1 firstWord secondWord thirdword fourthWord
MR1 some sentence written again.
MR1 some other sentence with variable length of words.
MR2 firstWord secondWord thirdword fourthWord
MR2 some sentence written again.
MR2 some other sentence with variable length of words.
MR3 ....

其中每个ID都与文件中的所有句子相关联,这显然是错误的。你知道吗

任何有助于实现上述预期结果的措施都将受到极大的赞赏。非常感谢。你知道吗


Tags: 文件withsomevariablelengthsentenceotheragain
1条回答
网友
1楼 · 发布于 2024-06-09 17:16:28

你可以这样做

  1. 分割每一行并将结果存储到一个变量中。

  2. 从位置1开始遍历列表中的所有元素。

  3. 为每个迭代打印第0个元素和切片列表中的元素。

示例:

>>> s = 'MR1 firstWord secondWord thirdword fourthWord'
>>> for i in s.split()[1:]:
        print(s.split()[0], i)


MR1 firstWord
MR1 secondWord
MR1 thirdword
MR1 fourthWord

确切的代码是

with open("file", "r") as myfile:
    lines = myfile.readlines()
    for line in lines:
        m = line.split()
        for i in m[1:]:
            print(m[0], i)

相关问题 更多 >