이 글은 python3.4.3에서 txt 텍스트를 한 줄씩 읽고 중복을 제거하는 방법을 주로 소개합니다. 이제 특정 참조 값이 있어 도움이 필요한 친구들이 참고할 수 있습니다. 주의해야 할 파일 쓰기 문제는 다음과 같습니다:
1. 문자 인코딩 2. 작업이 완료되는 즉시 파일 설명자를 닫습니다.
3. 코드 호환성
여러 가지 방법:#!/bin/python3
original_list1=[" "]
original_list2=[" "]
original_list3=[" "]
original_list4=[" "]
newlist1=[" "]
newlist2=[" "]
newlist3=[" "]
newlist4=[" "]
newtxt1=""
newtxt2=""
newtxt3=""
newtxt4=""
#first way to readline
f = open("duplicate_txt.txt","r+") # 返回一个文件对象
line = f.readline() # 调用文件的 readline()方法
while line:
original_list1.append(line)
line = f.readline()
f.close()
#use "set()" remove duplicate str in the list
# in this way,list will sort randomly
newlist1 = list(set(original_list1))
#newlist1 = {}.fromkeys(original_list1).keys() #faster
#rebuild a new txt
newtxt1="".join(newlist1)
f1 = open("noduplicate1.txt","w")
f1.write(newtxt1)
f1.close()
###################################################################
#second way to readline
for line in open("duplicate_txt.txt","r+"):
original_list2.append(line)
newlist2 = list(set(original_list2))
newlist2.sort(key=original_list2.index) #sort
#newlist2 = sorted(set(original_list2),key=l1.index) #other way
newtxt2="".join(newlist2)
f2 = open("noduplicate2.txt","w")
f2.write(newtxt2)
f2.close()
###################################################################
#third way to readline
f3 = open("duplicate_txt.txt","r")
original_list3 = f3.readlines() #读取全部内容 ,并以列表方式返回
for i in original_list3: #遍历去重
if not i in newlist3:
newlist3.append(i)
newtxt3="".join(newlist3)
f4 = open("noduplicate3.txt","w")
f4.write(newtxt3)
f4.close()
###################################################################
#fourth way
f5 = open('duplicate_txt.txt',"r+")
try:
original_list4 = f5.readlines()
[newlist4.append(i) for i in original_list4 if not i in newlist4]
newtxt4="".join(newlist4)
f6 = open("noduplicate4.txt","w")
f6.write(newtxt4)
f6.close()
finally:
f5.close()
중복 제거 전:
중복 제거 후(순서 없음):
아래 프로그램에는 파일 읽기 및 쓰기 작업과 연결 목록 작업이 포함되어 있습니다. 기사 시작 부분에 언급된 몇 가지 문제는 중국어가 아니므로 인코딩에 대해서는 신경 쓰지 않습니다. 여기에 언급하고 싶습니다:
f = open("test.txt","w") f.write(u"你好")

위 코드가 python2에서 실행되면 오류가 보고됩니다
프로그램이 유니코드 문자열을 직접 저장할 수 없기 때문에 오류가 보고됩니다. 인코딩해야 합니다. 저장하기 전에 str 유형의 이진 바이트 시퀀스로 변환됩니다. write() 메서드는 기본적으로 ascii 인코딩 형식을 사용하여 자동으로 인코딩을 변환하는데, ascii는 중국어를 처리할 수 없으므로 UnicodeEncodeError가 발생합니다. 올바른 방법은 write() 메서드를 호출하기 전에 형식을 수동으로 변환하고 utf-8 또는 gbk를 사용하여 str로 변환하는 것입니다.f = open("test.txt","w") text=u"你好" text=text.encode(encoding='utf-8') f.write(text)
close() 정보:
닫지 않으면 어떤 영향을 미치나요? 작업이 완료된 후 파일을 닫지 않으면 시스템에서 열 수 있는 파일 설명자 수가 제한되어 있으므로 시스템 리소스가 낭비됩니다. 리눅스는 65535입니다.
일반적으로 닫으면 괜찮지만 특별한 상황이 있을 수 있습니다. 예를 들어 open() 함수를 호출할 때 오류가 발생했고, close()를 호출하면 확실히 오류가 보고됩니다. 또 다른 방법은 write() 중에 디스크 공간이 부족하면 오류가 보고되고 close()가 실행될 기회가 없다는 것입니다. 올바른 방법은 예외를 잡기 위해 try Except를 사용하는 것입니다.
f = open("test.txt","w") try: text=u"你好" text=text.encode(encoding='utf-8') f.write(text) except: IOError as e: print("oops,%s"%e.args[0]) finally: f.close()
보다 우아한 작성 방법은 with...as를 사용하는 것입니다.
with open("test.txt","w") as f: text=u"你好" f.write(text.encode(encoding='utf-8'))
파일 개체는 오전 및 오후 관리자 프로토콜을 구현합니다. 프로그램이 with 문을 입력하면 파일 개체가 변수 f에 할당되고 프로그램이 실행될 때 close() 메서드가 자동으로 호출됩니다. 로 종료됩니다.
호환성 문제 정보:
python2와 python3의 open() 함수는 서로 다릅니다. 후자는 함수에서 문자 인코딩 형식을 지정할 수 있습니다.
python2와 python3 간의 호환성 open() 문제를 해결하는 방법은 무엇입니까?
io 모듈에서 open() 함수를 사용하세요. python2의 io.open은 python3의 open 함수와 동일합니다. _python
위 내용은 python3.4.3에서 txt 텍스트를 한 줄씩 읽고 중복을 제거하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

Arraysinpython, 특히 비밀 복구를위한 ArecrucialInscientificcomputing.1) theaRearedFornumericalOperations, DataAnalysis 및 MachinELearning.2) Numpy'SimplementationIncensuressuressurations thanpythonlists.3) arraysenablequick

Pyenv, Venv 및 Anaconda를 사용하여 다양한 Python 버전을 관리 할 수 있습니다. 1) PYENV를 사용하여 여러 Python 버전을 관리합니다. Pyenv를 설치하고 글로벌 및 로컬 버전을 설정하십시오. 2) VENV를 사용하여 프로젝트 종속성을 분리하기 위해 가상 환경을 만듭니다. 3) Anaconda를 사용하여 데이터 과학 프로젝트에서 Python 버전을 관리하십시오. 4) 시스템 수준의 작업을 위해 시스템 파이썬을 유지하십시오. 이러한 도구와 전략을 통해 다양한 버전의 Python을 효과적으로 관리하여 프로젝트의 원활한 실행을 보장 할 수 있습니다.

Numpyarrayshaveseveraladvantagesstandardpythonarrays : 1) thearemuchfasterduetoc 기반 간증, 2) thearemorememory-refficient, 특히 withlargedatasets 및 3) wepferoptizedformationsformationstaticaloperations, 만들기, 만들기

어레이의 균질성이 성능에 미치는 영향은 이중입니다. 1) 균질성은 컴파일러가 메모리 액세스를 최적화하고 성능을 향상시킬 수 있습니다. 2) 그러나 유형 다양성을 제한하여 비 효율성으로 이어질 수 있습니다. 요컨대, 올바른 데이터 구조를 선택하는 것이 중요합니다.

tocraftexecutablepythonscripts, 다음과 같은 비스트 프랙티스를 따르십시오 : 1) 1) addashebangline (#!/usr/bin/envpython3) tomakethescriptexecutable.2) setpermissionswithchmod xyour_script.py.3) organtionewithlarstringanduseifname == "__"

numpyarraysarebetterfornumericaloperations 및 multi-dimensionaldata, mumemer-efficientArrays

numpyarraysarebetterforheavynumericalcomputing, whilearraymoduleisiMoresuily-sportainedprojectswithsimpledatatypes.1) numpyarraysofferversatively 및 formanceforgedatasets 및 complexoperations.2) Thearraymoduleisweighit 및 ep

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기
