gpt-3.5-turbo-0301· OpenAI
WildChat-4.8M (AI2)
用python写对文本分词然后通过字典寻找字典词
- User
用python写对文本分词然后通过字典寻找字典词
- Assistant
这是一种可能的代码实现:
import jieba # 读入文本 with open('text.txt', 'r', encoding='utf-8') as f: content = f.read() # 分词 words = jieba.cut(content) # 构建词典 word_dict = {} with open('dictionary.txt', 'r', encoding='utf-8') as f: for line in f: word = line.strip() if word not in word_dict: # 避免重复添加 word_dict[word] = True # 寻找词典词 for word in words: if word in word_dict: print(word)其中,
text.txt是待分词的文本文件,dictionary.txt是保存了词典词的文本文件,每行一个词。这里使用了jieba库进行分词,也可以使用其他中文分词工具。在分词后,遍历词列表,若词在词典中出现,就打印出来。这里使用了一个字典存储词典中的词,并用True表示其存在与否,以便之后判断。可以根据需要改变词典的数据结构。
- User
并对词语进行位置标记
- Assistant
如果需要对词语进行位置标记,可以将原先的打印操作改为输出词语及其位置。对于不重复的词语,可以使用一个计数器记录其在文本中第几个出现,对于重复的词语,可以使用一个列表记录其出现位置。
以下是修改后的代码示例:
import jieba # 读入文本 with open('text.txt', 'r', encoding='utf-8') as f: content = f.read() # 分词 words = list(jieba.cut(content)) # 构建词典 word_dict = {} with open('dictionary.txt', 'r', encoding='utf-8') as f: for line in f: word = line.strip() if word not in word_dict: # 避免重复添加 word_dict[word] = True # 记录词语位置 positions = {} for i, word in enumerate(words): if word in word_dict: if word not in positions: positions[word] = [i+1] # 记录第一次出现的位置 else: positions[word].append(i+1) # 记录后续出现的位置 # 输出结果 for key, value in positions.items(): print(f'{key}: {" ".join(str(x) for x in value)}')其中,
positions是一个字典,key为词语,value为一个列表,记录词语在文本中出现的位置。在遍历词语时,首先判断其是否在词典中出现,如果是,则根据是否已经在positions中出现过作出相应的处理。输出结果时,将位置列表的元素通过空格连接为一个字符串。最终输出类似如下的结果:
中国: 6 19 美国: 3 12 18 日本: 9 22 ...