your programing

텍스트 파일을 문자열 변수로 읽고 줄 바꿈을 제거하는 방법은 무엇입니까?

lovepro 2020. 9. 28. 09:51
반응형

텍스트 파일을 문자열 변수로 읽고 줄 바꿈을 제거하는 방법은 무엇입니까?


다음 코드 세그먼트를 사용하여 파이썬에서 파일을 읽습니다.

with open ("data.txt", "r") as myfile:
    data=myfile.readlines()

입력 파일은 다음과 같습니다.

LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN
GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE

데이터를 인쇄하면

['LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN\n', 'GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE']

내가보기에 데이터는 list형태이다. 어떻게 문자열로 만드나요? 또한 여기 "\n"에서 "[", 및 "]"문자를 제거하려면 어떻게해야 합니까?


다음을 사용할 수 있습니다.

with open('data.txt', 'r') as file:
    data = file.read().replace('\n', '')

readline ()이 아닌 read () 사용

with open('data.txt', 'r') as myfile:
  data = myfile.read()

한 줄의 파일에서 읽을 수 있습니다.

str = open('very_Important.txt', 'r').read()

이것은 파일을 명시 적으로 닫지 않습니다.

CPython은 가비지 컬렉션의 일부로 종료 될 때 파일을 닫습니다.

그러나 다른 파이썬 구현은 그렇지 않습니다. 이식 가능한 코드를 작성하려면 with파일을 명시 적으로 사용 하거나 닫는 것이 좋습니다 . 짧은 것이 항상 좋은 것은 아닙니다. 참조 https://stackoverflow.com/a/7396043/362951를


모든 줄을 문자열로 결합하고 새 줄을 제거하려면 일반적으로 다음을 사용합니다.

with open('t.txt') as f:
  s = " ".join([x.strip() for x in f]) 

Python 3.5 이상에서는 pathlib사용하여 텍스트 파일 내용을 변수에 복사 하고 파일 을 한 줄로 닫을 수 있습니다 .

from pathlib import Path
txt = Path('data.txt').read_text()

그런 다음 str.replace사용 하여 줄 바꿈을 제거 할 수 있습니다 .

txt = txt.replace('\n', '')

with open("data.txt") as myfile:
    data="".join(line.rstrip() for line in myfile)

join ()은 문자열 목록을 결합하고 인수가없는 rstrip ()은 문자열 끝에서 줄 바꿈을 포함한 공백을 제거합니다.


이것은 read () 메서드를 사용하여 수행 할 수 있습니다.

text_as_string = open('Your_Text_File.txt', 'r').read()

또는 기본 모드 자체가 'r'(읽기)이므로 간단히 사용하십시오.

text_as_string = open('Your_Text_File.txt').read()

나는 잠시 동안이 주변에 바이올린을하고 사용을 선호했다 read와 함께 rstrip. 없이 rstrip("\n")파이썬은 문자열 끝에 줄 바꿈을 추가하는데, 대부분의 경우 그다지 유용하지 않습니다.

with open("myfile.txt") as f:
    file_content = f.read().rstrip("\n")
    print file_content

당신이 무엇을 쫓고 있는지 정확히 말하기는 어렵지만, 다음과 같이 시작해야합니다.

with open ("data.txt", "r") as myfile:
    data = ' '.join([line.replace('\n', '') for line in myfile.readlines()])

이것은 파일 객체를 닫는 한 줄의 복사-붙여 넣기 가능한 솔루션입니다.

_ = open('data.txt', 'r'); data = _.read(); _.close()

각 줄을 제거하고 최종 문자열로 연결할 수도 있습니다.

myfile = open("data.txt","r")
data = ""
lines = myfile.readlines()
for line in lines:
    data = data + line.strip();

이것은 또한 잘 작동합니다.


f = open('data.txt','r')
string = ""
while 1:
    line = f.readline()
    if not line:break
    string += line

f.close()


print string

splitlines()아직 아무도 언급 하지 않은 것에 놀랐습니다 .

with open ("data.txt", "r") as myfile:
    data = myfile.read().splitlines()

data이제 Variable 은 인쇄 할 때 다음과 같은 목록입니다.

['LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN', 'GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE']

줄 바꿈 ( \n) 이 없습니다 .

그 시점에서 콘솔에 라인을 다시 인쇄하고 싶은 것처럼 들리는데, for 루프를 사용하여 얻을 수 있습니다.

for line in data:
    print line

이것을 두 줄의 코드로 압축 할 수 있습니다 !!!

content = open('filepath','r').read().replace('\n',' ')
print(content)

파일이 다음과 같은 경우 :

hello how are you?
who are you?
blank blank

파이썬 출력

hello how are you? who are you? blank blank

질문의 [] 부분에 대해 언급 한 사람이 없다고 생각합니다. 각 줄을 변수로 읽을 때 \ n을 ''로 바꾸기 전에 여러 줄이 있었기 때문에 목록이 생성되었습니다. x의 변수가 있고 다음과 같이 출력하면

엑스

또는 print (x)

or str(x)

You will see the entire list with the brackets. If you call each element of the (array of sorts)

x[0] then it omits the brackets. If you use the str() function you will see just the data and not the '' either. str(x[0])


python3: Google "list comphrension" if the square bracket syntax is new to you.

 with open('data.txt') as f:
     lines = [ line.strip( ) for line in list(f) ]

Have you tried this?

x = "yourfilename.txt"
y = open(x, 'r').read()

print(y)

This works: Change your file to:

LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE

Then:

file = open("file.txt")
line = file.read()
words = line.split()

This creates a list named words that equals:

['LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN', 'GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE']

That got rid of the "\n". To answer the part about the brackets getting in your way, just do this:

for word in words: # Assuming words is the list above
    print word # Prints each word in file on a different line

Or:

print words[0] + ",", words[1] # Note that the "+" symbol indicates no spaces
#The comma not in parentheses indicates a space

This returns:

LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN, GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE

with open(player_name, 'r') as myfile:
 data=myfile.readline()
 list=data.split(" ")
 word=list[0]

This code will help you to read the first line and then using the list and split option you can convert the first line word separated by space to be stored in a list.

Than you can easily access any word, or even store it in a string.

You can also do the same thing with using a for loop.


file = open("myfile.txt", "r")
lines = file.readlines()
str = ''                                     #string declaration

for i in range(len(lines)):
    str += lines[i].rstrip('\n') + ' '

print str

Maybe you could try this? I use this in my programs.

Data= open ('data.txt', 'r')
data = Data.readlines()
for i in range(len(data)):
    data[i] = data[i].strip()+ ' '
data = ''.join(data).strip()

Regular expression works too:

import re
with open("depression.txt") as f:
     l = re.split(' ', re.sub('\n',' ', f.read()))[:-1]

print (l)

['I', 'feel', 'empty', 'and', 'dead', 'inside']

참고URL : https://stackoverflow.com/questions/8369219/how-to-read-a-text-file-into-a-string-variable-and-strip-newlines

반응형