我正在尝试将列表中的每个单词打印到单独的行中,但是它会将每个字母打印到单独的行上
Words = sentence.strip()
for word in sentence:
print (word)
我的完整代码(对任何想知道的人)是:
import csv
file = open("Task2.csv", "w")
sentence = input("Please enter a sentence: ")
Words = sentence.strip()
for word in sentence:
print (word)
for s in Words:
Positions = Words.index(s)+1
file.write(str(Words) + (str(Positions) + "\n"))
file.close()
答案 0 :(得分:0)
你忘了分句并在第一个循环中使用“单词”而不是“句子”。
#file = open("Task2.csv", "w")
sentence = input("Please enter a sentence: ")
Words = sentence.split()
for word in Words:
print (word)
for s in Words:
Positions = Words.index(s)+1
#file.write(str(Words) + (str(Positions) + "\n"))
#file.close()
<强>输出:强>
C:\Users\dinesh_pundkar\Desktop>python c.py
Please enter a sentence: I am Dinesh
I
am
Dinesh
C:\Users\dinesh_pundkar\Desktop>
答案 1 :(得分:0)
您需要使用str.split()
代替str.strip()
。
str.strip()
仅删除字符串中的前导和尾随空格:
>>> my_string = ' This is a sentence. '
>>> my_string.strip()
'This is a sentence.'
str.split()
执行您想要的操作,返回字符串中单词的列表;默认情况下,使用空格作为分隔符字符串:
>>> my_string = ' This is a sentence. '
>>> my_string.split()
['This', 'is', 'a', 'sentence.']
因此,您的代码应该更像:
words = sentence.split()
for word in sentence:
print(word)