在新行上连接字符串错误Python

2024-05-19 01:09:19 发布

您现在位置:Python中文网/ 问答频道 /正文

这个差不多了!你知道吗

获取用户输入,删除任何尾随的标点符号和非散列词,以发现tweet中的趋势。别问了!你知道吗

tweet = input('Tweet: ')
tweets = ''

while tweet != '':
  tweets += tweet
  tweet = input('Tweet: ')

print (tweets) # only using this to spot where things are going wrong!

listed_tweets = tweets.lower().rstrip('\'\"-,.:;!?').split(' ')
hashed = []

for entry in listed_tweets:
  if entry[0] == '#':
    hashed.append(entry) 

from collections import Counter
trend = Counter(hashed)

for item in trend:
  print (item, trend[item])

除了我得到的事实之外,它还能起作用:

Tweet: #Python is #AWESOME!
Tweet: This is #So_much_fun #awesome
Tweet: 
#Python is #AWESOME!This is #So_much_fun #awesome
#awesome!this 1
#python 1
#so_much_fun 1
#awesome 1

而不是:

#so_much_fun 1 
#awesome 2
#python 1

所以我没有在每一行输入的末尾得到一个空格,它会抛出我的列表!你知道吗

这可能很简单,但经过连续10个小时的自学,我的脑子乱七八糟的!!你知道吗


Tags: inputisthisitemtrendtweetstweetawesome
1条回答
网友
1楼 · 发布于 2024-05-19 01:09:19

这条线有问题:

  tweets += tweet

你把每一条推文都添加到上一条推文中。因此,前一条tweet的最后一个词与当前tweet的第一个词连接在一起。你知道吗

解决这个问题有多种方法。一种方法是一次处理一条tweet。从哈希标记的空数组开始,然后在循环中执行以下操作:

  1. 从用户那里读一行
  2. 如果行是空的,则跳出循环
  3. 否则,提取hashtags并将其添加到数组中
  4. 返回步骤1

下面的代码结合了这一思想,并进行了其他一些改进。注意交互式循环是如何编写的,这样代码中只有一个地方提示用户输入。你知道吗

hashtags = []

while True:                      # Read and clean each line of input.
  tweet = input('Tweet: ').lower().rstrip('\'\"-,.:;!?')
  if tweet == '':                # Check for empty input.
    break 
  print('cleaned tweet: '+tweet) # Review the cleaned tweet.
  for word in tweet.split():     # Extract hashtags.
    if word[0] == '#':
      hashtags.append(word)

from collections import Counter
trend = Counter(hashtags)

for item in trend:
  print (item, trend[item])

如果你继续处理推文,我怀疑你会发现你的推文清理过程是不够的。比如说,如果微博中间有标点符号呢?你迟早会想开始研究正则表达式的。你知道吗

相关问题 更多 >

    热门问题