2016-10-11 2 views
0

목록의 각 요소를 다른 파일에 쓰려고합니다.목록의 각 요소를 별도의 텍스트 파일로 작성하는 방법은 무엇입니까?

dataset = ['abc', 'def', 'ghi'] 

내가 루프를 원하는 목록을 통해리스트의 길이에 따라 텍스트 파일을 만듭니다

하자 우리가 목록을 말한다. 따라서이 경우 3 개의 텍스트 파일이 있어야하며 각각 abc, def 및 ghi의 내용을 갖습니다.

내 현재 코드는 다음과 같습니다 :

# This will read a text file, normalize it and remove stopwords from it using nltk. 
import nltk, io, math 
from nltk.corpus import stopwords 

# Read raw text 
targetFile = open('text.txt') 
rawtext = targetFile.read() 

# Removing stopwords 
stops = set(stopwords.words('english')) 
filtered_text = [i for i in rawtext.lower().split() if i not in stops] 

# Count Number of words 
total_words = len(filtered_text) 

# Divide them equally into 10 different lists 
chunk_size = math.floor(total_words/10) 
n_lists_of_words = [filtered_text[i:i + chunk_size] for i in range(0, len(filtered_text), chunk_size)] 
if(len(n_lists_of_words) > 10): 
    del n_lists_of_words[-1] 

# Lets make list of strings instead of list of lists 
list_of_str = [' '.join(x) for x in n_lists_of_words] 


# Create 10 different files from above 10 elements of n_list_of_words list 
for index, word in enumerate(n_lists_of_words): 
    with io.FileIO("output_text_" + str(index) + ".txt", "w") as file: 
     file.write(bytes(word), 'UTF-8') 

오류 메시지 :

Traceback (most recent call last): 
    File "clean_my_text.py", line 35, in <module> 
    file.write(bytes(word), 'UTF-8') 
TypeError: 'str' object cannot be interpreted as an integer 
+1

오류가 있습니까? –

+0

스크린 샷 –

+2

outfile : write (dataset [count])'목적에 맞지 않는'with open ("output_text_"+ str (count) + ".txt", "wb" – roganjosh

답변

0

감사합니다. 그것을 할 수 있습니다. 아래 해결책은 다음과 같습니다.

# This will read a text file, normalize it and remove stopwords from it using nltk. 
import nltk, io, math 
from nltk.corpus import stopwords 
from string import punctuation 

# Read raw text 
targetFile = open('input_text.txt') 
rawtext = targetFile.read() 

# Remove punctuation 
def strip_punctuation(s): 
    return ''.join(c for c in s if c not in punctuation) 
filtered_punc = strip_punctuation(rawtext) 
print(filtered_punc) 

# Removing stopwords 
stops = set(stopwords.words('english')) 
filtered_text = [i for i in filtered_punc.lower().split() if i not in stops] 

# Count Number of words 
total_words = len(filtered_text) 

# Divide them equally into 10 different lists 
chunk_size = math.floor(total_words/10) 
n_lists_of_words = [filtered_text[i:i + chunk_size] for i in range(0, len(filtered_text), chunk_size)] 
if(len(n_lists_of_words) > 10): 
    del n_lists_of_words[-1] 

# Lets make list of strings instead of list of lists 
list_of_str = [' '.join(x) for x in n_lists_of_words] 

# Print list values in seperate files 
for index, word in enumerate(list_of_str): 
    with open("Output" + str(index) + ".txt", "w") as text_file: 
     print(word, file=text_file) 
1

귀하의 코드가 조금 잘못된 것입니다. 여기가 수정 된 마지막 줄입니다. file.write (bytes (dataset [count], 'UTF-8'))

+0

이렇게 작동하지 않습니다. 당신은 문자열 인코딩이 필요하지만 이것을 좋아하지는 않습니다. 아래 답변에서했던 것처럼 다른 방법을 사용할 수 있습니다. –

관련 문제