如何按指定单词数拆分字符串生成新变量?
解决方案
按指定单词数X拆分
如果需要严格按设定的单词数量拆分,可以用shell脚本结合awk工具实现:
# 设定要拆分的单词数X X=9 # 处理后的文本行,可替换为从文件读取的内容 input_line="forecast=Mostly cloudy and cooler. Precipitation possible within 12 hours, possibly heavy at times. Windy" echo "$input_line" | awk -v split_words="$X" -F'=' '{ split($2, word_list, / /) first_part = "" second_part = "" for(i=1; i<=length(word_list); i++){ if(i <= split_words){ first_part = first_part (first_part ? " " : "") word_list[i] } else { second_part = second_part (second_part ? " " : "") word_list[i] } } print "forecast=" first_part print "forecast2=" second_part }'
执行后输出:
forecast=Mostly cloudy and cooler. Precipitation possible within 12 hours forecast2=possibly heavy at times. Windy
按句号拆分(更符合语义)
利用文本中自带的句号拆分,保证拆分后的内容语义完整,同样用awk实现:
input_line="forecast=Mostly cloudy and cooler. Precipitation possible within 12 hours, possibly heavy at times. Windy" echo "$input_line" | awk -F'=' '{ split($2, sentence_list, /\./) first_part = sentence_list[1] "." second_part = "" for(i=2; i<=length(sentence_list); i++){ if(sentence_list[i] != ""){ second_part = second_part (second_part ? ". " : "") sentence_list[i] } } if(second_part != "") second_part = second_part "." print "forecast=" first_part print "forecast2=" second_part }'
执行后输出:
forecast=Mostly cloudy and cooler. forecast2=Precipitation possible within 12 hours, possibly heavy at times. Windy.
Python实现方案
按指定单词数拆分
input_line = "forecast=Mostly cloudy and cooler. Precipitation possible within 12 hours, possibly heavy at times. Windy" split_words = 9 key, content = input_line.split('=', 1) word_list = content.split() forecast_val = ' '.join(word_list[:split_words]) forecast2_val = ' '.join(word_list[split_words:]) print(f"forecast={forecast_val}") print(f"forecast2={forecast2_val}")
按句号拆分
input_line = "forecast=Mostly cloudy and cooler. Precipitation possible within 12 hours, possibly heavy at times. Windy" key, content = input_line.split('=', 1) sentence_list = [s.strip() for s in content.split('.') if s.strip()] if len(sentence_list) >= 2: forecast_val = f"{sentence_list[0]}." forecast2_val = '. '.join(sentence_list[1:]) + '.' else: forecast_val = content forecast2_val = "" print(f"forecast={forecast_val}") print(f"forecast2={forecast2_val}")
内容的提问来源于stack exchange,提问作者BobW
相关产品推荐
相关产品推荐

