![](/img/trans.png)
[英]Python TypeError: sequence item 0: expected str instance, NoneType found
[英]TypeError: sequence item 12: expected str instance, NoneType found
這是我的代碼:
import re
with open('newfiles.txt') as f:
s = f.read()
uniquelist = []
error = re.findall(r"[\w]+|[^\s\w]", (s))
for word in error:
if word not in uniquelist:
uniquelist.append(word)
print ("Here are the words in their first appearing index form: ")
my_indexes = ' '.join(str(uniquelist.index(word)+1) for word in error)
print (my_indexes)
file = open("newfiletwo.txt","w")
file.write (' '.join(str(my_indexes)))
file.close()
file = open("newfilethree.txt","w")
file.write(' '.join(uniquelist))
file.close()
word_base = None
with open('newfilethree.txt', 'rt') as f_base:
word_base = [None] + [z.strip() for z in f_base.read().split()]
sentence_seq = None
with open('newfiletwo.txt', 'rt') as f_select:
sentence_seq = [word_base[int(i)] for i in f_select.read().split()]
print(my_indexes)
print(' '.join(sentence_seq))
它獲取一個文本文件,並返回其中的單詞和標點的位置(索引)。 如果重復,則給出第一個遇到的位置索引。 這樣,就打印出索引。 其次,在將單獨的單詞保存為文件和索引列表之后,我嘗試使用它們重新創建文本。 因此,最終輸出應該是標點符號本身的原始句子。 但是不幸的是,當程序運行到最后一行代碼時,出現此錯誤:
Traceback (most recent call last):
File "E:\Python\Final.py", line 26, in <module>
print(' '.join(sentence_seq))
TypeError: sequence item 12: expected str instance, NoneType found
有人知道問題出在哪里嗎?
您可以如下包裝該print(" ".join(sentence_seq))
並發布結果:
try:
print(" ".join(sentence_seq))
except TypeError:
print("Broken sentence: " + repr(sentence_seq))
raise
這不是修復程序 (但與上面類似,對於進行故障排除可能很有用):
print(" ".join(filter(None, sentence_seq)))
將刪除None
,但不會解決為什么它們首先為None
原因。
這是一個解決方法 :
my_indexes = ' '.join(str(uniquelist.index(word)) for word in error)
和
word_base = [z.strip() for z in f_base.read().split()]
您要在索引中添加1,然后在列表的開頭添加“ None
” ...刪除不再重現的兩個問題。
這不是答案,這僅是為了方便查看-Bjorn這是顯示的結果:
'They' <class 'str'>
'say' <class 'str'>
'it' <class 'str'>
"'" <class 'str'>
's' <class 'str'>
'a' <class 'str'>
'dog' <class 'str'>
"'" <class 'str'>
's' <class 'str'>
'life' <class 'str'>
',' <class 'str'>
'They' <class 'str'>
None <class 'NoneType'>
'They' <class 'str'>
'They' <class 'str'>
'They' <class 'str'>
'say' <class 'str'>
它輸出上面顯示的內容,但是程序的目的是打印此內容:
They say it's a dog's life, but for Estrella, born without her front legs, she's adapted to more of a kangaroo way of living. The Peruvian mutt hasn't let her disability hold her back, gaining celebrity status in the small town of Tinga Maria.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.