读取TXT文件内容到词典,以逗号和换行符为分割单位

读取TXT文件内容到词典,以逗号和换行符为分割单位
def open_dict(Dict = 'hh', path=r'data/Textming'):
path = path + '%s.txt' % Dict
dictionary = open(path, 'r', encoding='utf-8')
dict = []
for word in dictionary:
word = word.strip('\n'or',')
dict.append(word)
return dict
用or对吗,没报错,但是没结果

可以参考博客 python split指定多个分隔符,链接:https://blog.csdn.net/haodawei123/article/details/99543776

代码给出了 open_dict 函数部分:


import re
def open_dict(Dict = 'hh', path=r'data/Textming'):
    path = path + '%s.txt' % Dict
    dictionary = open(path, 'r', encoding='utf-8')
    dict = []
    for word in dictionary:
        word = re.split('[\n,]', word)
        for i in word:
            if i == '':
                continue
            dict.append(i)

    return dict

img

img

用正则表达式试试
https://blog.csdn.net/weixin_43313213/article/details/84582673

img


没问题呀 你是不是没写print