ValueError: substring not found, please save me

ValueError: substring not found, please save me

因此,我正在尝试制作一个排序器,按其在纸张上的时间顺序对文本进行排序。

算法:

def ordered(o, p):
    return sorted(o, key=lambda x: p.index(x))

print(ordered(text, ee))

不幸的是,它returns是这样的:

ValueError: substring not found

我尝试更改参数,因为我上次 运行 它成功了。有人能帮我吗?提前致谢。

正文如下:

ee = '''
The Civil War: Secession and Strengths/Weaknesses

Secession
The 1860 presidential race showed just how divided the nation had become. The Republicans were united behind Lincoln. The Democrats, however, had split between Northern and Southern factions [faction: a group of people within a larger group who have different ideas from the main group] , with Northern Democrats nominating Stephen Douglas for president and Southern Democrats supporting John C. Breckinridge of Kentucky. The election became even more confusing when a group called the Constitutional Union Party nominated John Bell of Tennessee.
Abraham Lincoln Is Elected President With his opposition divided three ways, Lincoln sailed to victory, but it was an odd victory. Lincoln won the presidential election with just 40 percent of the votes, all of them cast in the North. In ten Southern states, he was not even on the ballot.
For white Southerners, the election of 1860 delivered an unmistakable message. The South was now in the minority. It no longer had the power to shape national events or policies, and Southerners feared that, sooner or later, Congress would try to abolish slavery. And that, wrote a South Carolina newspaper, would mean “the loss of liberty, property, home, country—everything that makes life worth having.”
The South Secedes from the Union In the weeks following the election, talk of secession filled the air. Alarmed senators formed a committee to search for yet another compromise that might hold the nation together. They knew that finding one would not be easy, but they still had to do something to stop the rush toward disunion and disaster.
The Senate committee held its first meeting on December 20, 1860. Just as the senators began their work, events in two distant cities dashed their hopes for a settlement.
In Illinois, a senator named Lyman Trumbull asked President-Elect Abraham Lincoln whether he could support a compromise on slavery. Lincoln's answer was clear. He would not interfere with slavery in the South, and he would support enforcement of the Fugitive Slave Act. However, Lincoln drew the line at letting slavery extend into the territories. On this question, he declared, “Let there be no compromise.”
Meanwhile, in Charleston, South Carolina, delegates attending a state convention voted that same day—December 20, 1860—to leave the Union. The city went wild as church bells rang and crowds filled the streets, roaring their approval. A South Carolina newspaper boldly proclaimed, “The Union Is Dissolved!” Six more states soon followed South Carolina's lead, and in February 1861, those states joined together as the Confederate States of America.
The Civil War Begins On March 4, 1861, Lincoln became president of the not-so-united United States. In his inaugural address, Lincoln stated his belief that secession was both wrong and unconstitutional. He then appealed to the rebellious states to return in peace. “In your hands, my dissatisfied fellow countrymen, and not in mine,” he said, “is the momentous issue of civil war.”

The following month on April 12, 1861, Confederates in Charleston, South Carolina, forced the issue when they opened fire on Fort Sumter, a federal fort in Charleston Harbor. After more than 30 hours of heavy shelling, the defenders of the fort hauled down the Stars and Stripes and replaced it with the white flag of surrender.
The news that the Confederates had fired on the American flag unleashed a wave of patriotic fury in the North. All the doubts that people had about using force to save the Union vanished. A New York newspaper reported excitedly, “There is no more thought of bribing or coaxing the traitors who have dared to aim their cannon balls at the flag of the Union . . . Fort Sumter is temporarily lost, but the country is saved.”
The time for compromise was over. The issues that had divided the nation for so many years would now be decided by a civil war.








North Versus South
President Abraham Lincoln's quick-and-clear response to the attack on Fort Sumter was to call for 75,000 volunteers to come forward to preserve the Union. At the same time, Jefferson Davis, the newly elected president of the Confederacy, called for volunteers to defend the South. For the first time, Americans were fighting a civil war.
Strengths and Weaknesses of the North The North began the war with impressive strengths. Its population was about 22 million, compared to the South's 9 million. Additionally, with about 90 percent of the nation's manufacturing and most of its banks, the North was both richer and more technologically advanced than the South.
The North had geographic advantages, too. It had more farms than the South to provide food for troops, and its land contained most of the country's iron, coal, copper, and gold. The North controlled the seas, and its 21,000 miles of railroad track allowed troops and supplies to be transported wherever they were needed.
The North's greatest weakness was its military leadership. At the start of the war, about one-third of the nation's military officers resigned and returned to their homes in the South. During much of the war, Lincoln searched for effective generals who could lead the Union to victory.
Strength and Weaknesses of the South In contrast to the North, the South's great strength was its military leadership. Most of America's best military officers were Southerners who chose to fight for the Confederacy, which was not an easy decision for many of them. Colonel Robert E. Lee, for example, was not a supporter of either slavery or secession, but he decided that he could not fight against his native Virginia. Lee resigned from the U.S. Army to become commander in chief of the Confederate forces.
The South had geographic advantages as well. To win the war, the North would have to invade and conquer the South, but the sheer size of the South made this a daunting task. The South, in contrast, could win simply by defending its territory until Northerners became tired of fighting.
The South did have an important geographic disadvantage. If the Union gained control of the Mississippi River, it would divide the Confederacy in two.
The South's main weaknesses were its economy and its transportation systems. The region's agriculturally based economy could not support a long war, and the South had few factories to produce guns and other military supplies. The Confederacy also faced serious transportation problems because the South lacked the railroads needed to haul troops and supplies over long distances.
Abraham Lincoln Versus Jefferson Davis The North's greatest advantage was its newly elected president, Abraham Lincoln. Through even the darkest days of the war, Lincoln never wavered from his belief that the Union was perpetual—never to be broken. Throughout his presidency, Lincoln related the preservation of the Union to the ideals of the American Revolution. In his first inaugural address, he said that the Union was begun by the American Revolution, “matured and continued” by the Declaration of Independence, and affirmed by the Constitution.
At the time of the secession crisis, Jefferson Davis was a U.S. senator from Mississippi. A firm believer in states' rights, he resigned his seat in the Senate when Mississippi left the Union. Like Lincoln, Davis often spoke of the American Revolution. When Southerners formed their own government, Davis said in his inaugural address, they “merely asserted a right which the Declaration of Independence of 1776 had defined to be inalienable.” He believed the South was fighting for the same freedom cherished by the nation's founders.









    '''

这是必须由函数排序的提取文本:

text = ['in Charleston, South Carolina',
        'On March 4, 1861',
        'In his inaugural address',
        'six more states soon followed south carolina',
        'Confederates in charleston, south carolina',
        'after more than 30 hours of heavy shelling',
        'The time for a compromise was over',
        'The news that the confederates had been fired',
        'Republican candidate abraham lincoln won']

还有输出,我不知道。我是运行它,以便我可以在大文本中找到这些摘录的精确顺序。

str.index 找不到您要搜索的子字符串时,就会出现您遇到的错误。您可以在一个更简单的示例中看到这一点:

"some string".index("foo") # not found, raises ValueError

有几种方法可以解决这个问题。

一种选择是使用不同的字符串方法来搜索您的子字符串。 str.find 方法以与 str.index 相同的方式搜索子字符串,但它 returns -1 而不是在未找到子字符串时引发异常。这可能是您想要的,也可能不是您想要的,因为它会在所有匹配某处的子串之前对不匹配的子串进行排序。

另一种选择是先过滤您的输入以查看哪些字符串不匹配,然后再尝试对它们调用 index 以准确找到它们匹配的 位置 。可能您可以通过某种方式转换它们来解决问题,或者您可以跳过这些子字符串。例如:

text = [substring for substring in text if substring in ee] # exclude non-matching strings

最后一个选择是确定这是您的输入数据的问题,并在源头进行修复。也许你不应该有任何不匹配的子字符串。如果是这种情况,您应该弄清楚哪些不匹配以及原因,并修复它们!我会注意到您的几个字符串(如 "abraham lincoln" 和 "south carolina")中有一些奇怪的大写字母,如果正文中的大写字母不同,它们将不匹配。在这种情况下,从 str.index 获取异常是一项功能,而不是错误,因为它指出了数据错误!

问题是 text 列表中的某些字符串在文本中找不到,这就是 index() 引发 ValueError 异常的原因。您可以在排序之前过滤数据并排除额外的元素,或者使用 find() 而不是 index(),因为如果未找到元素,它会 returns -1(而不是引发异常)。使用后一种方法,您将得到一个列表,其中文本中未找到的元素位于开头,这可能与您的目标不符。