Python:字符串列表
问题描述:
我想查看.txt文件并在其中创建单词列表。我希望这些单词是字符串,但输出使它们成为列表。Python:字符串列表
import csv, math, os
os.chdir(r'C:\Users\jmela\canopy')
f=open("romeo.txt")
words = []
for row in csv.reader(f):
line = str(row)
for word in line.split():
if word not in words:
print word
words.append(word)
words.sort()
print words
有谁知道我在做什么错?
答
根据您的最新评论,看起来并不像您真的需要使用csv阅读器。只是试试这个:
words = []
for line in open("romeo.txt", "r"):
for word in line.split():
if word not in words:
words.append(word)
words.sort()
print words
和凯文建议,使用set(),而不是列表。
答
你可以使用set
来保留你的话。这会给你一个独特的单词列表。任何非alpha字符并转换为空格。该行被分成单词和小写以确保它们匹配。
word_set = set()
re_nonalpha = re.compile('[^a-zA-Z ]+')
with open(r"romeo.txt", "r") as f_input:
for line in f_input:
line = re_nonalpha.sub(' ', line) # Convert all non a-z to spaces
for word in line.split():
word_set.add(word.lower())
word_list = list(word_set)
word_list.sort()
print word_list
这将使你持有下列单词的列表:
['already', 'and', 'arise', 'breaks', 'but', 'east', 'envious', 'fair', 'grief', 'is', 'it', 'juliet', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'who', 'window', 'with', 'yonder']
更新还去除任何标点。
+0
确保占用额外的空格或连字符 – ytpillai
答
不要将文本文件读为csv。只需删除所有标点符号和非字母/非空格字符,如下所示:
def replacePunct(string):
alphabets = " abcdefghijklmnopqrstuvwxyz"
for s in string:
if s not in alphabets:
string = string.replace(s, " ")
replacePunct(string)
string = string.split()
string = [x for x in string if x != " "]
return {set(string): len(string)}
+0
以普通文本文件的形式读取文件,并为每一行运行此程序 – ytpillai
为什么在地球上,您将行转换为字符串,然后将其拆分? – Kasramvd
这并不直接解决您的问题,但如果您想要一个没有重复值的集合,请考虑使用集合。 – Kevin
你正在得到一个字符串列表,你可能会混淆它,因为它们中的一些已经有'['在其中。请参阅@Kasra评论为什么 – yuvi