写一个函数,读取文本,文本每一行是词语和空格和bio标签,用两个列表分别获取文本和标签
时间: 2024-05-09 19:15:13 浏览: 13
可以使用 Python 的文件操作和字符串操作来实现此函数:
```python
def read_text(text_file):
words = [] # 用于存储文本
labels = [] # 用于存储标签
with open(text_file, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip() # 去除行尾的换行符等空白字符
if not line: # 如果行为空则跳过
continue
parts = line.split() # 将行按空格分割成词语和标签
word, label = parts[0], parts[1] # 第一个部分是词语,第二个部分是标签
words.append(word)
labels.append(label)
return words, labels
```
使用方法:
```python
words, labels = read_text('text.txt')
print(words)
print(labels)
```
其中 `text.txt` 是包含文本和标签的文件,例如:
```
Hello B-greeting
world I-greeting
! O
How B-question
are I-question
you O
doing O
? O
```