5.编写程序输入一句话。若其中有新词语未在jieba词库中,输入新词语(多个新词语中文逗号间隔),将其添加到词库后统计中文词语个数;若没有新词语,输入空白行,统计中文词语个数。
时间: 2023-07-16 16:17:30 浏览: 42
这里提供一个 Python 实现的示例代码:
```python
import jieba
sentence = input("请输入一句话:")
new_words = input("请输入新词语(多个新词语中文逗号间隔):")
if new_words:
# 将新词语添加到词库
for word in new_words.split(','): # 中文逗号
jieba.add_word(word)
# 对句子进行分词
words = jieba.cut(sentence)
count = 0
for word in words:
# 判断是否为中文词语
if '\u4e00' <= word <= '\u9fa5':
count += 1
print("中文词语个数为:", count)
```
运行程序后,会依次提示输入一句话和新词语。如果没有新词语,可以直接回车输入空白行。程序会将新词语添加到 jieba 的词库中,然后对输入的句子进行分词,并统计其中的中文词语个数。最后输出统计结果。
相关问题
5.编写程序输入一句话。若其中有新词语未在jieba词库中,输入新词语多个新词语中文逗号问隔),将其添加到词库后统计中文词语个数; 若没有新词语,输入空白行,统计中文词语
好的,这是一个编程问题,需要用到Python和jieba库。以下是代码实现:
```python
import jieba
# 输入一句话
sentence = input("请输入一句话:")
# 切分句子
words = jieba.cut(sentence)
# 统计中文词语个数
count = 0
for word in words:
if word.encode('utf-8').isalpha():
count += 1
# 判断是否有新词语
new_words = input("请输入新词语(多个新词语用中文逗号隔开):")
if new_words:
# 将新词语加入词库
new_words_list = new_words.split(',')
for word in new_words_list:
jieba.add_word(word)
# 重新切分句子
words = jieba.cut(sentence)
# 统计中文词语个数
count = 0
for word in words:
if word.encode('utf-8').isalpha():
count += 1
# 输出结果
print("中文词语个数为:", count)
```
运行程序后,可以输入一句话和新词语(如果有的话),程序会自动统计中文词语个数,并将新词语添加到jieba词库中。注意,输入新词语时,多个新词语之间需要用中文逗号隔开。
给定一个字符串列表,其中大部分是中文词语。去掉其中不是中文词语的词
可以使用Python中的中文分词库jieba来实现。首先需要下载jieba库,然后使用以下代码:
```python
import jieba
def filter_chinese_word(words):
new_words = []
for word in words:
is_chinese = True
for char in word:
if not ('\u4e00' <= char <= '\u9fa5'):
is_chinese = False
break
if is_chinese:
new_words.append(word)
return new_words
# 示例
words = ['我', '爱', 'Python', '编程']
words = filter_chinese_word(words)
print(words)
```
这里的`filter_chinese_word`函数会遍历输入的字符串列表中的每一个字符串,判断其中是否只包含中文字符,如果是则将其添加到新的列表中。最后返回新的列表即为去除非中文词语后的结果。