在python中,如何从.txt文件中导入单词而不是任何标点符号?

时间:2016-10-08 18:55:26

标签: python python-3.x split

例如,我有一个内容为:

的txt文件
  

块引用

star, year, op, ed
ad, ed, offer, year
  

块引用

我想导入它们并形成一个列表,其中每行都作为子列表:     [ '明星', '年', '运', '编辑'],[ '广告', '编辑', '报价', '年'] 所以我使用下面的命令:

  

块引用

list = []
with open ("file_name", 'r') as f:
    for line in f:
        split_line = line.split()
        list.append(split_line)
f.close()

但是当我打印列表时,结果是:

  

块引用

[['star,','year,','op,','ed'],['ad,','ed,','offer,','year']]

那么我怎样才能得到一个只包含单词而不是任何标点符号的列表?

2 个答案:

答案 0 :(得分:0)

您只需要用逗号和空格分割:

with open ("file_name") as f:
    result = [line.split(', ') for line in f]

请注意,在使用whith语句时,无需手动关闭文件。这正是with在块结束时的作用。另外请注意,不要使用python内置名称命名变量名。

作为此任务的另一种替代方法(以及更多pythonic方法),您可以使用csv模块,该模块将使用分隔符自动分割您的行(默认情况下为逗号)。

import csv
with open ("file_name") as f:
    spam_reader = csv.reader(f) # you can pass the delimiter to reader function (if its something else rather than comma)
    rows = list(spam_reader) 

答案 1 :(得分:0)

分裂函数中的

尝试给出#34;,"像这样的论点。

split_line = line[:-2].split(", ")

希望这有帮助。