美文网首页工作生活
python实现指定字符串交换

python实现指定字符串交换

作者: 全村希望gone | 来源:发表于2019-07-03 15:30 被阅读0次

前言

我想实现的功能过于复杂,我都不知道我能不能用语言表述清楚,花了五六个小时写了这个程序,还是好好陈述一下需求吧。

因为我做命名实体识别嘛,我昨天想起来把数据扩充一下,怎么扩充呢,就是把相同类型的实体互换一下位置。例如 把这两个互换,就可以实现扩充数据集的目的了。再对其它类型的实体也互换,例如 之类。
所以我们来整理下需求。

需求

一个大方向就是把同种类型的实体互换,并将互换后的数据写进一个文件中,当作扩充的数据集。

如何实现实体互换呢?

  • 识别所有类型的实体并把它们放入不同的列表中,见程序段1;
  • 实现互换之前,需要知道用什么换?这里我用random.shuffle函数打乱实体list得到一个新的list B,将list A中的元素替换为list B的元素,见程序段2;
  • 有了list A和list B,就可以替换了,将list A对应的元素替换为list B的元素,见程序段3;
  • 替换完成,写入文件,见程序段4。

看起来好像不是很复杂,其实里面有很多坑需要跨过去,只有自己动手写才会知道问题在哪儿,编程真有意思。

import random

a = []
b = []
with open('1.txt', encoding='utf8') as file:
    for line in file:
        line = line.strip().split(' ')
        if len(line) == 2:
            a.append(line[0])
            b.append(line[1])
        else:
            a.append('Newline')
            b.append('Newline' + '\n')
with open('2.txt', 'w', encoding='utf8') as file2:
    for index, value in enumerate(a):
        file2.write(value + ' ' + b[index] + ' ')
loc = ''
name = ''
org = ''
loc_list = []
name_list = []
org_list = []
entity = ''
entity_list = ['LOC', 'ORG', 'NAME', 'TITLE', 'RACE', 'PRO', 'EDU', 'CONT']
# all_entity_list是双重列表,子列表是每种实体的列表
all_entity_list = []
all_entity_list_copy = []
# 生成LOC实体列表
# 用random.shuffle会改变loc_list的所有副本,即便你在使用shuffle之前就copy了一份,还是会被改掉。
# 所以我用一个新的空列表来接收原列表的值
# 程序段1:识别不同类型的实体并分别存入两个list中,这是因为后面shuffle操作会打乱list,所以多保存一个list方便实现之后的替换。
for ind, val in enumerate(entity_list):
    part_entity_list = []
    # 得从这儿开始就创建copy
    part_entity_list_copy = []
    for index, value in enumerate(b):
        if value.find(val) != -1:
            entity += a[index] + ' ' + value + ' '
            if value.find('E-' + val) != -1:
                part_entity_list.append(entity)
                part_entity_list_copy.append(entity)
                entity = ''
    all_entity_list.append(part_entity_list)
    all_entity_list_copy.append(part_entity_list_copy)
# print(all_entity_list)
# 保留原列表,并生成shuffle后的列表
# all_entity_list_copy = []
# loc_list_copy=loc_list
# print('*****',all_entity_list_copy)
# shuffle all_entity_list中的子列表
# 程序段2:打乱原实体list
all_entity_list_shuffle = []
for part_entity_list in all_entity_list:
    random.shuffle(part_entity_list)
    all_entity_list_shuffle.append(part_entity_list)
# 验证是否shuffle成功
print('*****', all_entity_list_copy)
print('*****', all_entity_list_shuffle)


file3 = open('2.txt', encoding='utf8')
# 程序段3:将list A中的元素替换为list B的元素
with open('4.txt', 'w', encoding='utf8') as file4:
    # 对每一行而言
    for i in file3:
        # 对于不同类型的实体,我需要嵌套多个for循环
        for ind, part_entity_list in enumerate(all_entity_list_copy):
            # 进入每个子列表
            for index, value in enumerate(part_entity_list):
                # print(value+'\n')
                # print(all_entity_list[ind][index]+'\n')
                if i.find(value) != -1:
                    # print(value+'\n')
                    # print(all_entity_list_shuffle[ind][index]+'\n')

                    i = i.replace(value, all_entity_list[ind][index])
                    # 当我在一个句子中找到第一个要被替换的字符串后,先替换,然后就跳出for循环,
                    # 不然的话程序会一直检测这个句子中是否还有要被替换的字符串,那我之前做的替换就会被后面的所取代。
                    break
        file4.write(i)

# 程序段4:生成一个新的打乱后的文件5.txt
words=[]
labels=[]
with open('4.txt', encoding='utf-8') as file:
    for line in file:
        line = line.strip().split(' ')
        for num in range(len(line)):
            if (num+1)%2==0:
                labels.append(line[num])
            else:
                words.append(line[num])

with open('5.txt', 'w',encoding='utf-8') as f:
    for num in range(len(labels)):
        f.write(words[num]+' '+labels[num]+'\n')

file5 = open('5.txt', encoding='utf-8')
with open('6.txt', 'w', encoding='utf-8') as file6:
    text = file5.read()
    file6.write(text.replace('Newline', ''))

效果图

源文件

现文件


剩下的就是把源文件和现文件复制粘贴到一起作为一个数据集了,不知道这样会不会提升模型精度,但愿吧。

相关文章

  • python实现指定字符串交换

    前言 我想实现的功能过于复杂,我都不知道我能不能用语言表述清楚,花了五六个小时写了这个程序,还是好好陈述一下需求吧...

  • python学习笔记1_find()

    python find()方法:Python find() 方法检测字符串中是否包含子字符串 str ,如果指定 ...

  • 数字的补数

    题目: 题目的理解: 将整数转化为二进制字符串,然后将1和0交换。 python实现 提交 // END 有些时候...

  • Python strip()、split()和rstrip()方

    1. Python strip() 语法描述: Python strip() 方法用于移除字符串头尾指定的字符(默...

  • Python数组

    python查看字符串中指定字符非重叠出现的次数 python反转数组内容 Python数组排序1 python数...

  • 字符串部分反转

    一、题目:将字符串指定部分反转,如"abcdefg"反转后为"abfedcg" 二、实现 方式一 1.把指定字符串...

  • Python字符串替换的两种实现方法

    Python实现字符串的两种方法。 方法一:使用python字符串的内置方法replace方法实现替换def st...

  • 2018-07-09-Python endswith()方法

    Python endswith() 方法用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回...

  • 自学Python:Python ljust()方法

    Python ljust() 方法返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原...

  • Python index()方法

    Python index() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结...

网友评论

    本文标题:python实现指定字符串交换

    本文链接:https://www.haomeiwen.com/subject/hpuqhctx.html