常用Python文件

# -*- coding: utf-8 -*-
"""
Created on Wed Jun 28 18:42:33 2017

@author: lmt
"""
import re
import numpy as np

‘‘‘
该程序实现对giza++后的对齐双语平行语料抽取对齐词汇关系
建立源语言到目标语言的映射矩阵,编号从0开始,将对齐文件中的NULL当作第一个词语
如果词语之间存在对齐关系,则将对齐矩阵matrixST[s][t]位置值设置为1,其它为0

‘‘‘
def alig_pairs(filepath):
    matrixZeroOne = []
    pattern1 = re.compile(r‘ \(\{([0-9 ]*)\}\) ?‘)
    # print(pattern1)
    f = open(filepath,‘r‘)#,encoding=‘utf-8‘)
    line=f.readline()
    #matrix = np.zeros()
    while(True):
        if not line:
            break   
        target = f.readline().strip().split()
        source = f.readline().strip()
        #match= pattern1.findall(source) # 使用Pattern匹配文本,获得匹配结果,无法匹配时将返回None
        source_word = pattern1.split(source)
        # print(source_word)
        s_l = len(source_word)//2-1#-1不考虑null
        t_l = len(target)
        #print(s_l)
        #print(t_l)
        matrixTS = np.zeros((t_l,s_l))
        #print(matrixST.shape)
        #从null开始对齐i=0。如果不考虑null,从第二位开始,i=2
        i=2
        while( i < len(source_word)-2):
            index = source_word[i+1]
            if index != ‘‘ and index !=‘ ‘:
                s = index.strip().split()
                # print(s)
                for s_ind in s:
                    #设置对齐矩阵
                    matrixTS[int(s_ind)-1][int((i-2))//2]=1
                    #print(i//2-1)
                    #该语句抽取对齐词语队
                    #print(source_word[int(i)],target[int(s_ind)-1])
            i+=2
        # print(matrixTS)
        matrixZeroOne.append(matrixTS)
        # print(matrixTS.shape)
        #因为对齐这个矩阵是动态生成的,所以在这里进行矩阵的合并

#print(i)            
        #print(source_word)
        #if match:
            #print (match)
            #print (‘yes‘)
        line=f.readline()
        #print(target)
        #print(source)
        
   
    f.close()
    return matrixZeroOne
#alig_pairs(‘test.txt‘)
#alig_pairs(‘117-06-28.183340.lmt.A3.final‘)
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

# -*- coding: utf-8 -*-
import codecs
def get_matrix():
        #print(‘程序进入process‘)
    Chinese = codecs.open("result/result_cn",‘r‘,encoding = ‘utf-8‘)
    English = codecs.open(‘result/result_en‘, ‘r‘, encoding = ‘utf-8‘)
    # result_eng = codecs.open(‘result/swap_en‘, ‘w‘, encoding = ‘utf-8‘)
    # result_chi = codecs.open(‘result/swap_cn‘, ‘w‘, encoding = ‘utf-8‘)
    # eng_chi = codecs.open(‘result/en_to_cn‘,‘w‘,encoding = ‘utf-8‘)

english_sentence_count = 0
    chinese_sentence_count = 0
        
    chinese_word = []
    chinese_sentence = []

for line in Chinese.readlines():
        pair = line.strip().split()
        if len(pair) == 4:
            swap = pair[1]
            pair[1] = pair[2]
            pair[2] = swap
            s = pair[0] + " " + pair[1] + " " + pair[2] + " " + pair[3]
            chinese_word.append(s)
            # result_chi.write(pair[0] + "    " + pair[1] + "    " + pair[2] + "    " + pair[3] + "\n")
        if len(pair) == 0:
            chinese_sentence.append(chinese_word)
            chinese_word = []
            # result_chi.write("\n")
            chinese_sentence_count += 1

english_word = []
    english_sentence = []
    for line in English.readlines():
        pair = line.strip().split()
        if len(pair) == 4:
            swap = pair[1]
            pair[1] = pair[2]
            pair[2] = swap    
            s = pair[0] + " " + pair[1] + " " + pair[2] + " " + pair[3]
            english_word.append(s)
            # result_eng.write(pair[0] + "    " + pair[1] + "    " + pair[2] + "    " + pair[3] + "\n")
        if len(pair) == 0:
            english_sentence.append(english_word)
            english_word = []
            # result_eng.write("\n")
            english_sentence_count += 1

if english_sentence_count < chinese_sentence_count:
        min_count = english_sentence_count
    else:
        min_count = chinese_sentence_count

matrix = []
    if len(english_sentence) == len(chinese_sentence):
        i = 0
        while i < len(english_sentence):
            chinese_sentence_length = len(chinese_sentence[i])
            english_sentence_length = len(english_sentence[i])#获得当前句子的行列值

english_chinese = [["0" for col in range(english_sentence_length + 1)] for row in range(chinese_sentence_length + 1)]
            
            col = 1
            while col <= english_sentence_length:
                english_chinese[0][col] = english_sentence[i][col - 1]
                col += 1
            
            row = 1
            while row <= chinese_sentence_length:
                english_chinese[row][0] = chinese_sentence[i][row - 1]
                row += 1
            # for row in range(chinese_sentence_length):
            #     for col in range(english_sentence_length):
            #         eng_chi.write(english_chinese[row][col] + "    ")
            #     eng_chi.write("\n")
            # eng_chi.write("\n")
            #每次放进去的矩阵,其实规模是不一样大的
            matrix.append(english_chinese)
            i = i + 1
    else:
        print(‘error‘)

# for j in range(len(matrix)):
    #     for row in range(len(matrix[j])):
    #         s = ""
    #         for col in range(len(matrix[j][row])):
    #             s += matrix[j][row][col]
    #             s += "    "
    #         print(s)
        
    return matrix, chinese_sentence
#matrix,_ = get_matrix()            
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------

#-*-coding:utf-8-*-
import os  
import string  
   
def count(filepath):  
    total = 0 #总行数  
    countPound = 0 #注释行数  
    countBlank = 0 #空行数  
    line = open(filepath,‘r‘)#,encoding=‘utf-8‘)
    for li in line.readlines(): #readlines()一次性读完整个文件  
        total += 1  
        if not li.split(): #判断是否为空行  
            countBlank +=1  
        li.strip()  
        if li.startswith(‘#‘):  
            countPound += 1  
    print(file)  
    print("countBlank:%d" % countBlank)  
    print("countPound:%d" % countPound)  
    print("total:%d" % total)  
 
 
count(‘result_cn‘)

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

#-*-coding:utf-8-*-
def bijiao():  
     f1=open(‘lmt.txt‘,‘r‘)  
     f2=open(‘lh.txt‘,‘r‘)  
     count=0     #统计行数  
     dif=[]      #统计不同的数量序列  
     for a in f1:  
          b=f2.readline()  
          count+=1  
          if a!=b:  
              dif.append(count)  
     f1.close()  
     f2.close()  
     return dif    
c=bijiao()  
if c==0:  
     print(‘两个文件一样!‘)  
else:  
     print(‘有%d处不同‘% len(c))  
     for each in d:  
          print(‘%d行不一样‘% each)

时间: 2025-01-06 22:22:30

常用Python文件的相关文章

Python文件常用的三个变量

1 '''Python文件常用的三个变量 2 __doc__.__name__.__file__ 3 4 __doc__——用来显示文件的注释,文件的注释都是写在文件的开头, 5 以""" doc """标注的内容.可以直接调用.也可以查看其他文件的注释, 6 如导入了一个Queue模块,可以用print Queue.__doc__来查看 7 8 __name__——用来检查是否是主文件的一个重要方法,比如是主动执行的此文件, 9 那么值就是'_

Python常用模块——文件复制模块shutil

Python常用模块--文件复制模块shutil shutil模块 高级的文件.文件夹.压缩包处理模块 shutil.copyfileobj(fsrc, fdst) 将文件内容拷贝到另一个文件中 import shutil shutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w')) shutil.copyfile(src, dst) 拷贝文件 shutil.copyfile('f1.log', 'f2.log') #目标文件无需存在

python中常用的文件和目录操作(一)

常用的文件操作 1. 打开文件 open,它是一个内置函数,可以直接调用 语法:file object = open(file_name, [access_mode]),这里我们会创建一个file对象 参数:file_name--要访问的文件名称的字符串值,access_mode--决定了打开文件的模式:只读.写入.追加等.这个参数是非强制的,默认文件访问模式为只读(r) 返回值:返回一个文件对象 模 式 解释 r  以只读方式打开文件.文件的指针将会放在文件的开头.这是默认模式 r+ 打开一个

python文件相关操作

Python文件相关操作 打开文件 打开文件,采用open方法,会将文件的句柄返回,如下: f = open('test_file.txt','r',encoding='utf-8') 在上面的代码中,open()方法进行打开文件等相关操作,open()方法其中第一个参数是要打开的文件的文件路径,第二个参数是对要打开文件要执行的权限,第三个参数是文件采用字符编码. 而open()方法返回的内容叫做文件句柄.我们可以打印返回的文件句柄来看下: f = open('test_file.txt','r

Python文件输入输出

http://blog.csdn.net/pipisorry/article/details/37769669python文件输入输出教程 python文件中的读入科学计数法的数字 float(word_dist) 皮皮blog python文件读取 内置函数open() 得到一个文件对象(file object):open(filename, mode='r') 函数参数 1. 模式mode: 模式 描述 r 以只读方式打开文件.文件的指针将会放在文件的开头.这是默认模式. rb 以二进制格式

pythoning——9:python文件操作

字面意思,文件操作,无非就是找到文件,打开文件,写入/删除文件,找不到文件就去创建文件,并没有什么特殊的.如果你是这么认为的,那就太天真了,在python中提供了更为合理的数据管理方式.并非是你想像中的那么简单. 首先是打开文件,打开文件需要调用open函数,提供文件名,及打开方式.打开方式有(默认为r): r: 只读模式 w: 只写模式 a: 追加模式(从文件结尾追加) r+: 读写模式 w+: 读写模式(会先清空,后写入,然后读取,写读更合理吧) a+: 读写模式(还是只会从结尾处追加) r

python文件编码说明 coding=utf-8

python 支持3种编码声明,一般常用能见到下面两种 1.# -*- coding: utf-8 -*- 这种写法是为了兼容Emacs的编码声明 2.短一点,但Emacs不能用# coding=utf-8 短一点,但Emacs不能用 之所以要声明未编码类型 ,主要是中文出错的问题. 在python 文件开头(一般是第一行或第二行),用来说明你的Python源程序文件用使用的编码.缺省情况下你的程序需要使用ascii码来写,但如果在其中写中文的话,python解释器一般会报错,但如果加上你所用的

Python 文件和目录操作总结

Python文件和目录操作总结: 1. Python 中os模块基本命令 头文件 import os # 提供对操作系统进行调用的接口 os常用指令 1 os.getcwd() # 获取当前工作目录,即当前python脚本工作的目录路径 === linux: pwd 2 os.chdir("dirname") # 改变当前脚本工作目录:相当于shell下cd 3 os.curdir # 返回当前目录: ('.') 4 os.pardir # 获取当前目录的父目录字符串名:('..')

Python 全栈开发:python文件处理

python文件处理 打开文件的模式 file常用函数 一.打开文件,关闭文件 操作文件的流程: #1. 打开文件,得到文件句柄并赋值给一个变量 #2. 通过句柄对文件进行操作 #3. 关闭文件 open()方法:返回一个file对象 语法格式: #file = open(filename,mode,encoding) #打开文件 #文件操作 文件的读和写 #file.close() #关闭文件 常用参数 filename: 要打开的文件名称(文件的路径) mode: 打开文件的模式(见上图)